Redux的使用

352 阅读2分钟

1.概述

Redux,它是一个数据层框架,它将所有数据放到公共Store中进行管理,当一个组件改变了Store中的数据,Store可以很好很快的同步给其他组件                    

2.Redux工作流程

1.名词解释

Store:数据仓库

React Components:页面组件层

Action Creators:分发层

Reducers:数据操作层

2.工作流程

组件要获取或修改Store中数据,它不能直接去操作Store,而是需要通过Action进行通信,它通过Action Creators分发他想要获取或修改什么数据的指令,指令到达Store后,Store就将接收到的指令和之前的State交给Reducer去处理,Reducers在接到Store转来的previousState和Action后,它根据Action指令去改变previousState,得到新得newState,然后将新的newState返还给Store;此时,Store用新得State替换旧的State。

3.代码演示(TodoList)

1.创建仓库

store/index.js

import { createStore } from 'redux'import reducer from './reducer' // 引入reducerconst store = createStore(reducer)export default store

2.创建reducer

store/reducers.js

import { CHANGE_INPUT_VALUE, ADD_TODO_ITEM, DEL_TODO_ITEM } from './actionTypes'const defaultState = {  inputValue: '',  list: [],}// reducer接收state,但是不能去改变它const reducer = (state = defaultState, action) => {  if (action.type === CHANGE_INPUT_VALUE) {    const newState = { ...state, inputValue: action.value }    return newState  }  if (action.type === ADD_TODO_ITEM) {    const newState = {      ...state,      list: [...state.list, state.inputValue],      inputValue: '',    }    return newState  }  if (action.type === DEL_TODO_ITEM) {    const newState = {      ...state,    }    newState.list.splice(action.value, 1)    return newState  }  return state}export default reducer

3.创建actionTypes

store/actionTypes.js

const CHANGE_INPUT_VALUE = 'change_input_value'
const ADD_TODO_ITEM = 'add_todo_item'const DEL_TODO_ITEM = 'del_todo_item'export { CHANGE_INPUT_VALUE, ADD_TODO_ITEM, DEL_TODO_ITEM }

4.创建actionCreators

store/actionCreators.js

import { CHANGE_INPUT_VALUE, ADD_TODO_ITEM, DEL_TODO_ITEM } from './actionTypes'export const getInputChangeAction = (value) => ({  type: CHANGE_INPUT_VALUE,  value,})export const addTodoItemAction = () => ({  type: ADD_TODO_ITEM,})export const delTodoItemAction = (value) => ({  type: DEL_TODO_ITEM,  value,})

5.页面中使用

import React, { useState } from 'react'import { Button, Input, List } from 'antd'import store from './store'import {  getInputChangeAction,  addTodoItemAction,  delTodoItemAction,} from './store/actionCreators'const TodoList = () => {  const [state, setState] = useState(store.getState())  // input改变  const handleChange = (e) => {    const action = getInputChangeAction(e.target.value)    store.dispatch(action)  }  // add  const handleAdd = () => {    const action = addTodoItemAction()    store.dispatch(action)  }  // del  const handleDel = (index) => {    const action = delTodoItemAction(index)    store.dispatch(action)  }  const handleStoreChange = () => {    setState(store.getState())  }  // 监听Store改变,重新拉取Store中的最新数据  store.subscribe(handleStoreChange)  return (    <>      <div style={{ display: 'flex' }}>        <Input          style={{ width: 200 }}          value={state.inputValue}          onChange={handleChange}        />        <Button type="primary" onClick={handleAdd}>          提交        </Button>      </div>      <List        size="large"        bordered        dataSource={state.list}        renderItem={(item, index) => (          <List.Item key={item} onClick={() => handleDel(index)}>            {item}          </List.Item>        )}      />    </>  )}export default TodoList

4.补充

  • store是唯一的
  • 只有store能够改变自己的内容,reducer只是拿到旧数据生成新数据,把新数据返回给store,store自己进行数据的更新,所以reducer不要改变store的数据
  • reducer必须是纯函数,纯函数就是给定固定输入,有固定输出,不会有任何副作用
  • 核心API:createStore(创建仓库)、store.dispatch(分发action)、store.getState(获取仓库数据)、store.subscribe(监听仓库变化,执行回调)