1.创建store仓库
使用redux中createStore方法创建store
import {createStore} from 'redux';
const store = createStore()
export default store
2.创建reducer
创建一个匿名函数设置两个参数 state和action 然后 把state return出去
const defaultState = {
inputValue: "Write Somthing",
list: ["8:00,开会", "9:00,二开", "10:00,散开"],
};
export default (state = defaultState, action) => {
return state;
};
3.将reducer传入store中
将组件中需要使用redux的state放到reducer的state中,再将reducer中的匿名函数传入到store中的createStore中
import {createStore} from 'redux';
import reducer from '../reducer';
const store = createStore(reducer)
export default store
4.使用store中的state
此时在组件中引入store,再通过.getState()方法获取到store中的state值
import React, { Component } from "react";
import { Input, Button, List } from "antd";
import store from './store/index';
class TodoList extends Component {
constructor(props){
super(props)
console.log(store.getState())
this.state=store.getState()
}
render() {
return (
<div>
<div style={{ margin: "10px" }}>
<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>)}
>
</List>
</div>
</div>
);
}
}
export default TodoList;