欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

七十九、TodoList示例 深入Redux的工作流

程序员文章站 2022-07-02 22:42:52
...
2020/11/20、 周五、今天又是奋斗的一天。

@Author:Runsen

React,也有了自己去构建一些应用的信心,那会是一种非常棒的感觉。你学会了管理状态,一切看起来井井有条。但是,很有可能这就到了你该学习 Redux 的时候了。

Redux-devtools插件

Redux DevTools是一个开源项目,是为谷歌浏览器用户打造的一款实用调试插件,主要适用于开发者使用,使用该插件可以有效地对应用程序或者网页的状态进行调试操作。

我上传到CSDN,下载链接:https://download.csdn.net/download/weixin_44510615/13130629

因为我是window系统, 需要添加window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()

七十九、TodoList示例 深入Redux的工作流

七十九、TodoList示例 深入Redux的工作流

七十九、TodoList示例 深入Redux的工作流

Redux

七十九、TodoList示例 深入Redux的工作流

原理:React首先改变store里面的数据state,先要开发一个Aciton,然后通过dispath方法传递给store,store再把之前的数据和Action转化的数据在Reducers进行判断和对比,Reducers本身就是一个函数,返回新的state,store就替换之前的state。

下面举添加点击的Redux的工作流流程。
七十九、TodoList示例 深入Redux的工作流

七十九、TodoList示例 深入Redux的工作流

七十九、TodoList示例 深入Redux的工作流

七十九、TodoList示例 深入Redux的工作流

具体代码

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
import store from './store';

class TodoList extends Component {
  constructor(props) {
    super(props)
    this.state = store.getState()
    this.handleInputChange = this.handleInputChange.bind(this)
    this.handleStoreChange = this.handleStoreChange.bind(this)
    this.handleBtnClick = this.handleBtnClick.bind(this)
    store.subscribe(this.handleStoreChange);
    console.log( this.state)
  }

  render() {
    return(
      <div>
        <div>
          <Input 
          value={this.state.inputValue}
          placeholder="Todo info" 
          style={{width:'300px',marginRight:'10px' }}
          onChange={this.handleInputChange}></Input>
          <Button type="primary"
          onClick={this.handleBtnClick}>提交</Button>
        </div>
        <List
        bordered
        style={{width:'300px',marginTop:'10px' }}
        dataSource={this.state.list}
        renderItem={(item,index) => (
          <List.Item onClick={this.handleItemDelete.bind(this,index)}>
            {item}
          </List.Item>
        )}
        />
      </div>
    )
  }
  
  handleInputChange(e) {
    const action = {
      type: 'change_input_value',
      value: e.target.value
    }
    store.dispatch(action)
  }

  handleStoreChange() {
		this.setState(store.getState());
  }
  
  handleBtnClick() {
    const action = {
      type: 'add_todo_item',
    }
    store.dispatch(action)
  }

  handleItemDelete(index) {
    const action = {
      type: 'delete_todo_item',
      index
    }
    store.dispatch(action)
  }
}

export default TodoList;

reducer.js

/* eslint-disable import/no-anonymous-default-export */
const defaultState = {
  inputValue : '123',
  list: [1,2]

}

export default (state = defaultState , action) => {
  if (action.type === 'change_input_value'){
    const newState = JSON.parse(JSON.stringify(state));
    newState.inputValue = action.value
    return newState
  }

  if (action.type === 'add_todo_item'){
    const newState = JSON.parse(JSON.stringify(state));
    newState.list.push(newState.inputValue)
    newState.inputValue ='';
    return newState
  }

  if (action.type === 'delete_todo_item'){
    const newState = JSON.parse(JSON.stringify(state));
    newState.list.splice(action.inbdex,1)
    return newState
  }

  return state;
}

index.js

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

const store = createStore(
  reducer,
  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
  );

export default store;

ActionTypes和ActionCreator拆分

由于全部代码在TodoList.js写死了,不容易维护,需要进行ActionTypes和ActionCreator拆分

具体目录如下
七十九、TodoList示例 深入Redux的工作流

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
import store from './store';
import { getInitList, getInputChangeAction, getAddItemAction, getDeleteItemAction } from './store/actionCreators'


class TodoList extends Component {
  constructor(props) {
    super(props)
    this.state = store.getState()
    this.handleInputChange = this.handleInputChange.bind(this)
    this.handleStoreChange = this.handleStoreChange.bind(this)
    this.handleBtnClick = this.handleBtnClick.bind(this)
    store.subscribe(this.handleStoreChange);
    console.log( this.state)
  }

  render() {
    return(
      <div>
        <div>
          <Input 
          value={this.state.inputValue}
          placeholder="Todo info" 
          style={{width:'300px',marginRight:'10px' }}
          onChange={this.handleInputChange}></Input>
          <Button type="primary"
          onClick={this.handleBtnClick}>提交</Button>
        </div>
        <List
        bordered
        style={{width:'300px',marginTop:'10px' }}
        dataSource={this.state.list}
        renderItem={(item,index) => (
          <List.Item onClick={this.handleItemDelete.bind(this,index)}>
            {item}
          </List.Item>
        )}
        />
      </div>
    )
  }
  
  componentDidMount() {
		const action = getInitList();
		store.dispatch(action);
	}

	handleInputChange(e) {
		const action = getInputChangeAction(e.target.value);
		store.dispatch(action);
	}

	handleStoreChange() {
		this.setState(store.getState());
	}

	handleBtnClick() {
		const action = getAddItemAction();
		store.dispatch(action);
	}

	handleItemDelete(index) {
		const action = getDeleteItemAction(index);
		store.dispatch(action);
	}
}

export default TodoList;

actionCreators.js

import { GET_INIT_LIST, CHANGE_INPUT_VALUE, ADD_TODO_ITEM, DELETE_TODO_ITEM, INIT_LIST_ACTION } from './actionTypes';

export const getInputChangeAction = (value) => ({
	type: CHANGE_INPUT_VALUE,
	value
});

export const getAddItemAction = () => ({
	type: ADD_TODO_ITEM
});

export const getDeleteItemAction = (index) => ({
	type: DELETE_TODO_ITEM,
	index
});

export const initListAction = (data) => ({
	type: INIT_LIST_ACTION,
	data
});

export const getInitList = () => ({
	type: GET_INIT_LIST
});

actionTypes.js

export const CHANGE_INPUT_VALUE = 'change_input_value';
export const ADD_TODO_ITEM = 'add_todo_item';
export const DELETE_TODO_ITEM = 'delete_todo_item';
export const INIT_LIST_ACTION = 'init_list_action';
export const GET_INIT_LIST = 'get_init_list';

reducer.js

import { INIT_LIST_ACTION, CHANGE_INPUT_VALUE, ADD_TODO_ITEM, DELETE_TODO_ITEM } from './actionTypes'

const defaultState = {
	inputValue: '',
	list: []
}

// reducer 可以接受state,但是绝不能修改state
// 纯函数指的是,给定固定的输入,就一定会有固定的输出,而且不会有任何副作用
export default (state = defaultState, action) => {

	if (action.type === CHANGE_INPUT_VALUE) {
		const newState = JSON.parse(JSON.stringify(state));
		newState.inputValue = action.value;
		return newState;
	}

	if (action.type === INIT_LIST_ACTION) {
		const newState = JSON.parse(JSON.stringify(state));
		newState.list = action.data;
		return newState;
	}

	if (action.type === ADD_TODO_ITEM) {
		const newState = JSON.parse(JSON.stringify(state));
		newState.list.push(newState.inputValue);
		newState.inputValue = '';
		return newState;
	}
	if (action.type === DELETE_TODO_ITEM) {
		const newState = JSON.parse(JSON.stringify(state));
		newState.list.splice(action.index, 1);
		return newState;
	}
	return state;
}