useReducer

使用useReducer用来践行Flux/redux的思想

使用useReducer分四步

  • 创建初始值initialState
  • const reducer = (state, action) => {switch(action.type) {case:}}传入旧的数据state和创建所有操作action
  • const [state,dispatch] = useReducer(reducer,initialState)传给useReducer,得到读和写API,必须写在函数里面
  • dispatch({type:'add '})调用写的类型

总的来说,useReducer是useState的复杂版,所有useState的规则,useReducer都适用

例子

useState出现重复时,用useReducer

const initFormData = {
  name: "",
  age: 18,
  ethnicity: "汉族"
}
const reducer = (state, action) => {
  switch (action.type) {
    case 'patch': //更新
      return {...state, ...action.formData} //把旧的数据复制到一个对象,把新的数据复制到一个对象,把两个对象合并
    case "reset": //重置
      return initFormData
    default:
      throw new Error()
  }
}
const App = () => {
  console.log('App执行了一遍')
  const [formData, dispatch] = useReducer(reducer, initFormData)
  const onSubmit = () => {
  }
  const onReset = () => {
    dispatch({type: "reset"})
  }
  return (
    

{JSON.stringify(formData)}
) }

使用useReducer代替Redux

步骤

  • 将数据集中在一个store对象
  • 将所有操作集中在reducer
  • 创建一个Context
  • 创建对数据的读写API
  • 将第四步的内容放到Context.Provider
  • 用Context.Provider将Context提供给所有组件,所有标签,组件必须放在Context.Provider
  • 各个组件用useContext获取读写API

例子

在react-demo-usereducer文件里,查看git commit为''instead Redux''的版本

import React, {createContext, useContext, useEffect, useReducer} from 'react';

const store = {
  user: null,
  books: null,
  movies: null
}

const reducer = (state, action) => {//state旧的数据
  switch (action.type) {
    case "setUser":
      return {...state, user: action.user}
    case "setBooks":
      return {...state, books: action.books}
    case "setMovies":
      return {...state, movies: action.movies}
    default:
      throw new Error('undefined')
  }
}

const Context = createContext(null)

const App = () => {
  const [state, dispatch] = useReducer(reducer, store)

  return (
    
      
      
) } const User = () => { const {state, dispatch} = useContext(Context) useEffect(() => { ajax('/user').then(user => { dispatch({type: "setUser", user}) }) }, []) return (

个人信息

name: {state.user ? state.user.name : ''}
) } const Books = () => { const {state, dispatch} = useContext(Context) useEffect(() => { ajax('/books').then(books => { dispatch({type: "setBooks", books}) }) }, []) return (

我的书籍

    {state.books ? state.books.map(book =>
  1. {book.name}
  2. ) : "加载中......"}
) } const Movies = () => { const {state, dispatch} = useContext(Context) useEffect(() => { ajax('/movies').then(movies => { dispatch({type: "setMovies", movies}) }) }, []) return (

我的电影

{state.movies ? state.books.map(movie =>
  • {movie.name}
  • ) : "加载中......"}
    ) } function ajax(path) { return new Promise((resolve, reject) => { setTimeout(() => { if (path === '/user') { resolve({ id: 1, name: "Ryan" }) } else if (path === '/books') { resolve([ { id: 1, name: "JavaScript高级程序设计" }, { id: 2, name: "JavaScript 精粹" } ]) } else if (path === '/movies') { resolve([ { id: 1, name: "当下的力量" }, { id: 2, name: "时间简史" } ]) } else { alert("请求错误") } }, 2000) }) } export default App;

    模块化reducer

    从上一个例子可以看出,如果组件很多,把action的类型混在一起会变得杂乱不堪,因此需要模块化

    如何模块化呢?模块就是文件,把代码抽离成一个个文件,导入导出文件就是模块化

    难点:把reducer的函数变成对象,函数难合并,对象容易合并

    const obj = {
      ...userReducer,
      ...booksReducer,
      ...moviesReducer
    }
    const reducer = (state, action) => {//state旧的数据
      const fn = obj[action.type]
      if (fn) {
        return fn(state, action)//这个地方容易出错!!!!
      } else {
        throw new Error("unvalid type")
      }
    }
    

    你可能感兴趣的:(useReducer)