Redux

2020-09-04  本文已影响0人  gem_Y

学习来源: https://jspang.com/detailed?id=48#toc21
D:\wamp\www\react\study\reduxdemo

image.png

reducer.js(模块管理)

// 管理模块
const defaultState = {
  inputValue: 'write something',
  list: [
    '早上6点起床,锻炼身体',
    '中午下班睡觉一小时'
  ]
}
export default (state = defaultState, action) => {
  if (action.type === 'changeInput') {
    let newState = JSON.parse(JSON.stringify(state)) // 深拷贝 state
    newState.inputValue = action.value
    return newState
  }
  return state
}

store.js

import { createStore } from 'redux';
import reducer from './reducer'

const store = createStore(
  reducer,
  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
) // 创建数据存储仓库
export default store // 暴露出去

无状态组件 :todoListUI.js

import React from 'react';
import 'antd/dist/antd.css';
import { Input, Button, List } from 'antd';

const TodoListUi = (props) => {
  return ( 
    <div>
      <div>
        <Input
          onChange={props.changeInputValue}
          placeholder="Basic usage"
          style={{ width: '250px',margin: '20px'}} />
        <Button onClick={props.addItem}>增加</Button>
      </div>
      <div style={{margin:'10px',width:'300px'}}>
        <List
          header={<div>头部</div>}
          footer={<div>尾部</div>}
          bordered
          dataSource={props.list}
          renderItem={(item,index) => (
            <List.Item onClick={() => { props.delItem(index) }}> // 注意
              {item}
            </List.Item>
          )}
        />
      </div>
    </div>
  );
}
 
export default TodoListUi;

TodoList

import React, { Component } from 'react';
// import axios from 'axios'
import store from './store'
import { addItemAction, delItemAction, getTodoList } from './store/actionCreatores'
import TodoListUI from './TodoListUI'

class TodoList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: '',
      list: store.getState().list
    }
    // 订阅redux的状态
    store.subscribe(this.storeChange)
  }
  storeChange = () => {
    console.log('storeChange', store.getState())
    this.setState({
      list: store.getState().list
    })
  }

  changeInputValue = (e) => {
    this.setState({
      inputValue: e.target.value
    })
  }

  addItem = () => {
    const action = addItemAction(this.state.inputValue)
    store.dispatch(action)
  }

  delItem = (index) => {
    const action = delItemAction(index)
    store.dispatch(action)
  }

  render() { 
    return ( 
      <TodoListUI
        changeInputValue={this.changeInputValue}
        list={this.state.list}
        addItem={this.addItem}
        delItem={this.delItem}
      />
     );
  }
}
export default TodoList;
上一篇下一篇

猜你喜欢

热点阅读