create-react-app腳手架使用

1.安裝腳手架和路由css

npm i -g create-react-appvue

npm i -S react-router react-router-domreact

2.建立新項目es6

create-react-app 項目名稱ajax

3.運行項目vue-cli

npm startnpm

4.開始開發json

跟vue-cli和ng-cli很不一樣的是,react就算用了cli和原來引入api

1)書寫組件react-router

例如一個簡單的組件:

//test.component.js
import React,{Component} from React
import './test.css'

class Test extends Component {
    constructor(...args){
        super(...args)
    }    
    render(){
        return (
            <div className="test">
                test123
            </div>
        )
    }
}
export default Test

2)引入書寫路由

//App.js
import React,{Component} from React
import {BrowserRouter,Switch,Route,Link} from 'react-router-dom'
import Test1 from './test1.js'
import Test2 from './test2.js'
import Test3 from './test3.js'

class App extends Component {
    render(){
        return (
            <BrowserRouter>
                <div>
                    <Link to="/test3/123/">切換到test3</Link>
                    <Test1></Test1>
                    <Switch>
                        <Route path="/" component={Test2}></Route>
                        <Route path="/test3/:id/" component={Test3}></Route>
                    </Switch>
                </div>
            </BrowserRouter>
        )
    }
}
export default App

3)ajax請求用es6的fetch

//組件掛載完成時訪問接口
async componentDidMount(){
     let data = await (await fetch('http://localhost:8088/api/getData',
        // options
        {  method: 'POST',
            headers: { 
                'Accept': 'application/json', 
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ 
                user: 'miemie', 
                pass: '123456'
            }) 
        }
    ).json())
    this.setState({myList: data})
}
相關文章
相關標籤/搜索