Web前端之路程序员技术栈前端开发

前端之路——Redux(02)

2019-06-02  本文已影响8人  三点水滴

上一篇文章中提到,Redux是为了解决在复杂的应用中状态管理的工具。那么,该如何使用Redux呢?

Redux的使用

根据Redux的三大原则——全局唯一性、只读性、纯函数(修改)性,我们首先来看看Redux的组成

Redux的组成

除了作为一个状态管理中心所必备的功能之外,Redux还有以下特征:

如何集成Redux

Redux本身是作为一个状态管理工具,并不是和React绑定的。而React-Redux就是一个把React和Redux绑定的工具。使用React-Redux只是因为它可以帮助我们更好地在React中使用Redux,所以这里我们先考虑不使用中间件React-Redux的情况下,如何在React应用中使用Redux。

通过对Redux的剖析,我们大致也能归纳出使用Redux的步骤:

talk is cheap, show me the code.

说明如下:

    // store.js 这里为了方便,将整个Store及reducer、action都放在了一个文件
import { createStore } from 'redux'

const initialState = {
  index: 0,
  todoList: [],
}

export default createStore((state = initialState, { type, payload = {} }) => {
  const { index, status } = payload
  switch(type) {
    case 'NEW':
        {
          payload.key = state.index
          payload.status = 'UNDONE'
          return {
            todoList: [
              ...state.todoList,
              payload
            ],
            index: state.index + 1
          }
        }
    case 'DONE':
      return {
        todoList: state.todoList.map((todo, i) => {
          i === index ? todo.status = 'DONE' : todo
          return todo
        }),
        index: state.index
      }
    case 'UNDONE':
      return{
        todoList: state.todoList.map((todo, i) => {
          i === index ? todo.status = 'UNDONE' : todo
          return todo
        }),
        index: state.index
      }
    case 'TRASH':
      return{
        todoList: state.todoList.map((todo, i) => {
          i === index ? todo.status = 'TRASH' : todo
          return todo
        }),
        index: state.index
      }
    case 'RETRIVE':
      return{
        todoList: state.todoList.map((todo, i) => {
          i === index ? todo.status = 'UNDONE' : todo
          return todo
        }),
        index: state.index
      }
    default:
        return state
  }
})

这里创建了一个高阶组件,其中导入了Redux中的store,并在componentDidMountcomponentWillUnmount

订阅并且退订了store。

import React from 'react'
import store from '../models/store'

export const wrap = (WrappedComponent) => {
  return class extends React.Component {

    constructor(props) {
      super(props)
      this.state = {
        data: store.getState(),
      }
      this.dispatch = store.dispatch
    }

    componentDidMount() {
      this.unsubscribe = store.subscribe(() => this.setState({
        data: store.getState()
      }))
    }
    
    componentWillUnmount() {
      this.unsubscribe()
    }

    render() {
      const { data } = this.state;
      return (
        <WrappedComponent {...this.props} dispatch={this.dispatch} data={data} />
      )
    }
  }
}

这里是Home页面,通过utils.wrap(Home)来包装,获得了dispatch方法,通过dispatch能够向store发送更新状态的Action,从而完成对用户操作的响应

import React from 'react';
import ToDoList from '../../components/ToDoList/todolist'
import * as utils from '../../utils'

class Home extends React.Component {

  constructor(props) {
    super(props)
    
  }

  submit = (e) => {
    e.preventDefault()
    const { dispatch } = this.props
    dispatch({
      type: 'NEW',
      payload: {
        content: this.addToDo.value
      }
    })
    this.addToDo.value = ''
  }

  onDone = todo => {
    const { dispatch } = this.props
    dispatch({
      type: 'DONE',
      payload: {
        index: todo.key
      }
    })
  }

  onTrash = todo => {
    const { dispatch } = this.props
    dispatch({
      type: 'TRASH',
      payload: {
        index: todo.key
      }
    })
  }

  render() {
    const { data: { todoList } } = this.props
    return (
      <div>
        <form>
          <input name="todo" ref={ref => this.addToDo = ref} />
          <button type="submit" onClick={this.submit}>add</button>
        </form>
        <h2>新的TODOS</h2>
        <ToDoList
          onChange={this.onDone}
          onRemove={this.onTrash}
          todoList={todoList.filter(todo => todo.status === 'UNDONE')}
        ></ToDoList>
      </div>
    )
  }
}

export default utils.wrap(Home)
上一篇 下一篇

猜你喜欢

热点阅读