1.在src目录下新建一个store文件夹,并且在store文件夹中新建两个文件index.js和reducer.js
2.安装redux,在命令行中输入:
yarn add redux3.index.js文件中的代码:
//引入redux import { createStore } from 'redux'; import reducer from './reducer'; //创建store并且传递把reducer传递进来 const store = createStore(reducer); export default store;4.reducer.js中的代码
//state:所有数据信息 const defaultState = { inputValue: '123', list:[1,3] } //设置state的默认数据:defaultState export default (state = defaultState, action) => { return state; }4.在TodoList.js中先需要导入state文件夹下的index.js
import store from './store/index'将获取到的inputValue中的数据传递给input 将获取到的list中的数据传递给List TodoList.js的完整代码:
import React, { Component } from 'react'; import 'antd/dist/antd.css'; import {Input,Button,List } from 'antd'; import store from './store/index' class TodoList extends Component{ constructor(props) { super(props); //将获取到的store数据绑定给自己的this.state this.state = store.getState(); console.log(this.state); } render() { return ( <div> <div style={{marginTop:'10px',marginLeft:'10px'}}> <input value={this.state.inputValue} placeholder='输入框' style={{ width: '300px',marginRight:'5px' }}/> <Button type="primary">提交</Button> </div> <div> <List style={{marginTop:'10px', width:'300px'}} bordered dataSource={this.state.list} renderItem={item => (<List.Item>{item}</List.Item>)} /> </div> </div> ) } } export default TodoList;运行结果;