reactjs - 从状态创建对象
问题描述
我有两种状态:
const [firstState, setFirstState] = useState(6.5)
const [secondState, setSecondState] = useState(3.5)
我希望将这两种状态组合成一个对象,如下所示:
const [myObject, setMyObject] = useState({
first: {firstState},
second: {secondState}
});
//NOTE: This does not compile when i try to create state-object with state values.
然后我将对象作为道具发送到子组件,稍后用于显示。
<ChildComponent objectToChild={myObject}/>
将状态组合成一个对象的最佳实践是什么?
解决方案
他们是不同的选择
1.使用useState Hook
const [myObject, setMyObject] = useState({
first: firstState,
second: secondState
});
修改状态
setMyObject({...myObject, firstState })
2.使用useReducer
当您具有涉及多个子值的复杂状态逻辑或下一个状态取决于前一个状态时,useReducer 通常比 useState 更可取。
const initialState = {
first: 'name',
second: 'surname'
};
const reducer = (state, action) => {
switch (action) {
case 'first': return { ...state, first: state.first };;
case 'second': return { ...state, second: state.second };;
default: throw new Error('Unexpected action');
}
};
像使用它一样
const [state, dispatch] = useReducer(reducer, initialState);
推荐阅读
- javascript - axios 拦截器:自定义标头仅添加到 OPTIONS 请求中
- sql - 最后第二行代码中出现错误,错误为 00933。00000 -“SQL 命令未正确结束”。如何解决这个问题?
- javascript - 带有编辑选项的画布图像
- vue.js - 在 x-template 中获取 Vue.js 实例特定的组件数据
- spring-boot - org.thymeleaf.exceptions.TemplateProcessingException
- codeigniter - Codeigniter 3 验证错误未与回调函数一起显示
- tensorflow - 如何在 Arch linux 中降级到 cuda 10.0?
- javascript - 是否可以通过 html 标签、CSS 或 Javascript 启用 Google Chrome (v74) 暗模式?
- regex - 正则表达式:如何删除最后一个空行?
- c# - 升级 Chromedriver 以匹配 Chrome 版本 74。错误说 Chrome 必须在 70-73 之间