1.创建store仓库

使用redux中createStore方法创建store

  1. import {createStore} from 'redux';
  2. const store = createStore()
  3. export default store

2.创建reducer

创建一个匿名函数设置两个参数 state和action 然后 把state return出去

  1. const defaultState = {
  2. inputValue: "Write Somthing",
  3. list: ["8:00,开会", "9:00,二开", "10:00,散开"],
  4. };
  5. export default (state = defaultState, action) => {
  6. return state;
  7. };

3.将reducer传入store中

将组件中需要使用redux的state放到reducer的state中,再将reducer中的匿名函数传入到store中的createStore

  1. import {createStore} from 'redux';
  2. import reducer from '../reducer';
  3. const store = createStore(reducer)
  4. export default store

4.使用store中的state

此时在组件中引入store,再通过.getState()方法获取到store中的state值
image.png

  1. import React, { Component } from "react";
  2. import { Input, Button, List } from "antd";
  3. import store from './store/index';
  4. class TodoList extends Component {
  5. constructor(props){
  6. super(props)
  7. console.log(store.getState())
  8. this.state=store.getState()
  9. }
  10. render() {
  11. return (
  12. <div>
  13. <div style={{ margin: "10px" }}>
  14. <Input
  15. placeholder={this.state.inputValue}
  16. style={{ width: "250px", marginRight: "10px" }}
  17. />
  18. <Button type="primary">增加</Button>
  19. </div>
  20. <div style={{margin:'10px',width:'300px'}}>
  21. <List
  22. bordered
  23. dataSource={this.state.list}
  24. renderItem={item=>(<List.Item>{item}</List.Item>)}
  25. >
  26. </List>
  27. </div>
  28. </div>
  29. );
  30. }
  31. }
  32. export default TodoList;