我们实现一下,异步获取远程数据,然后将它显示在todolist 中。
异步数据获取,我们使用axios。
那么我们首先使用一下生命周期函数 componentDidMount ,在周期函数里面发送axios 请求。如下。
import React, {Component} from 'react';
import store from './store/index.js';
import {
getInputChangeAction,
getAddItemAction,
getDeleteItemAction
} from './store/actionCreators';
import TodoListUI from './TodoListUI';
import axios from 'axios';
class BeautifulToDoList extends Component {
constructor(props) {
super(props);
this.state = store.getState();
this.handleInputChange = this.handleInputChange.bind(this);
this.handleStoreChange = this.handleStoreChange.bind(this);
this.handleBtnClick = this.handleBtnClick.bind(this);
this.handleItemClick = this.handleItemClick.bind(this);
store.subscribe(this.handleStoreChange);
}
render() {
return (
<TodoListUI
inputValue={this.state.inputValue}
list={this.state.list}
handleInputChange={this.handleInputChange}
handleBtnClick={this.handleBtnClick}
handleItemClick={this.handleItemClick}
/>
)
}
componentDidMount() {
axios.get('api/list.json').then((res) => {
console.log(res);
})
}
handleInputChange(e) {
const action = getInputChangeAction(e.target.value);
store.dispatch(action);
}
handleStoreChange() {
this.setState(store.getState());
}
handleBtnClick() {
const action = getAddItemAction();
store.dispatch(action);
}
handleItemClick(index) {
const action = getDeleteItemAction(index);
store.dispatch(action);
}
}
export default BeautifulToDoList;
本来是准备用 Charles ,拦截http 请求,然后映射到本地文件的。但是Charles 怎么着也没有拦截到localhost 的请求,试了好久,应该是我没有配好,放弃。使用mockjs 吧。
mockjs 可以参考 https://github.com/nuysoft/Mock/wiki/Getting-Started
首先我们先下载安装mockjs 到项目中,使用代码 npm install mockjs --save-dev
安装好后,我们在src 下面新建一个文件mockdata.js 文件,然后在这个文件里写下面的内容。
import Mock from 'mockjs';
Mock.mock("api/list.json",{
"name": "Alice"
})
然后,我们启动服务器就,就在控制台显示数据了。
然后我们在componentDidMount 生命周期函数里,写下面的代码就好。(记得要引入mockdata.js)
import axios from 'axios';
import './mockdata';
componentDidMount() {
axios.get("api/list.json",{dataType: 'json'}).then( res => {
console.log(res.data);
const action = {
type: "init_List",
value: res.data.names
};
store.dispatch(action);
})
}
然后,在reducer.js 中添加下面的代码即可。
if (action.type === 'init_List') {
const newState = JSON.parse(JSON.stringify(state));
newState.names = action.value;
return newState;
}
好啦,现在项目初始化的 数组就是从远程获取的。