首先要安装Redux,打开终端输入以下命令:
npm install --save redux
一、编写创建store仓库
store是Redux工作流程中非常重要的一部分,它负责所有数据的管理。
首先在src目录下新建一个store文件夹,并在store下新建index.js文件。index.js就是整个项目的store文件,该文件代码内容如下:
import {createStore} from 'redux';//引入createStore方法
const store = createStore(); //创建数据存储仓库
export default store;
在store下新建文件reducers.js,内容如下:
const defaultState = {} //默认数据
export default (state = defaultState,action)=>{
return state
}
在store中引入reducer,再创建store:
import {createStore} from 'redux';
import reducer from './reducer';
const store = createStore(reducer) //reducer注入
export default store;
二、在store中初始化TodoList数据
在reducers.js文件的defaultState中添加inputValue和list属性:
const defaultState = {
inputValue : 'Write Something',
list: [
'早8点开晨会,分配今天的代码任务',
'早9点和项目经理开需求沟通会',
'早10点学习技术知识'
]
}
export default (state = defaultState,action)=>{
return state
}
三、组件获取store数据
引入store:
import store from './store'; //表示'./store/index.js'
TodoList.js文件:
import React, { Component } from 'react';
import 'antd/dist/antd.css';
import { Input , Button ,List} from 'antd';
import store from './store'; //表示'./store/index.js'
class TodoList extends Component {
constructor(props){
super(props);
console.log(store.getState());
this.state = store.getState();
}
render() {
return (
<div style={{margin:'10px'}}>
<div>
<Input
placeholder={this.state.inputValue}
style={{width:'250px', marginRight:'10px'}}
/>
<Button type="primary">增加</Button>
</div>
<div style={{margin:'10px',width:'300px'}}>
<List
bordered
dataSource={this.state.list}
renderItem={item=>(<List.Item>{item}</List.Item>)}
/>
</div>
</div>
);
}
}
export default TodoList;
运行结果:
store数据获取成功。