美文网首页
useReducer

useReducer

作者: 我是Msorry | 来源:发表于2021-01-09 09:58 被阅读0次

使用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 (
    <form onSubmit={onSubmit} onReset={onReset}>
      <div>
        <label >
          姓名
          <input value={formData.name} onChange={e=>dispatch({type:"patch",formData:{name: e.target.value}})}/>
        </label>
      </div>
      <div>
        <label >
          年龄
          <input value={formData.age} onChange={e=>dispatch({type:"patch",formData:{age: e.target.value}})}/>
        </label>
      </div>
      <div>
        <label >
          民族
          <input value={formData.ethnicity} onChange={e=>dispatch({type:"patch",formData:{age: e.target.value}})}/>
        </label>
      </div>
      <div>
        <button type="submit">提交</button>
        <button type="reset">重置</button>
      </div>
      <hr/>
      {JSON.stringify(formData)}
    </form>
  )
}

使用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 (
    <Context.Provider value={{state, dispatch}}>
      <User/>
      <hr/>
      <Books/>
      <Movies/>
    </Context.Provider>
  )
}

const User = () => {
  const {state, dispatch} = useContext(Context)
  useEffect(() => {
    ajax('/user').then(user => {
      dispatch({type: "setUser", user})
    })
  }, [])
  return (
    <div>
      <h1>个人信息</h1>
      <div>name: {state.user ? state.user.name : ''}</div>
    </div>
  )
}

const Books = () => {
  const {state, dispatch} = useContext(Context)
  useEffect(() => {
    ajax('/books').then(books => {
      dispatch({type: "setBooks", books})
    })
  }, [])
  return (
    <div>
      <h1>我的书籍</h1>
      <ol>
        {state.books ? state.books.map(book => <li key={book.id}>{book.name}</li>) : "加载中......"}
      </ol>
    </div>
  )
}

const Movies = () => {
  const {state, dispatch} = useContext(Context)
  useEffect(() => {
    ajax('/movies').then(movies => {
      dispatch({type: "setMovies", movies})
    })
  }, [])
  return (
    <div>
      <h1>我的电影</h1>
      {state.movies ? state.books.map(movie => <li key={movie.id}>{movie.name}</li>) : "加载中......"}
    </div>
  )
}

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

      本文链接:https://www.haomeiwen.com/subject/lutmrktx.html