react hooks(React中useReducer的理解与使用)
导读:这里以简单的语言描述一下useReducer的使用。也可自己查看官方文档(英文)...
这里以简单的语言描述一下useReducer的使用 。也可自己查看官方文档(英文)
useReducer的使用场景:
当一个state需要维护多个数据且它们之间互相依赖 。
这样业务代码中只需要通过dispatch来更新state ,繁杂的逻辑都在reducer函数中了 。一 、useReducer
demo:
function reducer(state, action){ //... } const [state, dispatch] = useReducer(reducer, { name: "qingying", age: 18 }); 1. useReducer主要作用就是更新state 。
参数:
第一个是 reducer 函数 ,这个函数返回一个新的state 。
后面再详述该函数的使用 。 第二个是 state 初始值 。返回值:
当前 state 。(可以在业务代码中获取 、操作的就是它 。) dispatch 函数 ,纯函数 ,用来更新state ,并会触发re-render。
(通俗地说 ,dispatch就是重新操作state的 ,会让组件重新渲染) 2. reducer函数作用:处理传入的state ,并返回新的state 。
参数:
接受当前 state 。 接受一个action ,它是 dispatch 传入的。返回值:
新的state 。
3. dispatch函数发送一个对象给reducer,即action 。
参数:
一个对象。
返回值: 无 。完整代码:
import { useReducer } from "react"; /* 当state需要维护多个数据且它们互相依赖时 ,推荐使用useReducer 组件内部只是写dispatch({...}) 处理逻辑的在useReducer函数中 。获取action传过来的值 ,进行逻辑操作 */ // reducer计算并返回新的state function reducer(state, action) { const { type, nextName } = action; switch (type) { case "ADD": return { ...state, age: state.age + 1 }; case "NAME": return { ...state, name: nextName }; } throw Error("Unknown action: " + action.type); } export default function ReducerTest() { const [state, dispatch] = useReducer(reducer, { name: "qingying", age: 12 }); function handleInputChange(e) { dispatch({ type: "NAME", nextName: e.target.value }); } function handleAdd() { dispatch({ type: "ADD" }); } const { name, age } = state; return ( <> <input value={name} onChange={handleInputChange} /> <br /> <button onClick={handleAdd}>添加1</button> <p> Hello,{name}, your age is {age} </p> </> ); }创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!