react-hooks - 当我需要进行大量计算时优化代码反应
问题描述
我在 React 中放了一个我的代码的小例子,我需要做很多计算,有没有最佳的方法来做到这一点?我希望值随着状态中的值的变化而变化。
const [data, setData] = useState(
a: 30,
b: 15,
c: 100,
d: 50
);
const [atot, setATot] = useState(data.a * 18);
const [btot, setBtot] = useState(data.b * d);
const [ctot, setCtot] = useState(data.c * 20);
...... here goes more variables
useEffect(() => {
setATot(data.a * 18);
setBtot(data.b * atot);
setCtot(data.c * 20);
...... here goes more variables
}, [data]);
return(
<div>value1: {atot}</div>
<div>value2: {btot}</div>
<div>value3: {ctot}</div>
)
像上面那样处理代码是一种好方法吗?
解决方案
在你的情况下,最好使用useReducer钩子
const initialState = { a: 30,
b: 15,
c: 100,
d: 50
};
function reducer(state, action) {
switch (action.type) {
case 'ATot':
return {...state, a: state.a * action.payload};
case 'BTot':
return {...state, b: state.b * action.payload};
default:
throw new Error();
}
}
推荐阅读
- java - 如何根据相应的行将jTable值插入数据库?
- c# - 从上午 07:00 开始每 8 小时运行一次 Quartz.NET 以执行特定作业
- azure - 如何通过 Azure REST API 获取 IOT Edge Modules 的运行状态?(不是来自“获取设备上的模块”API 调用的 connectionState 或状态)
- firebase - PlatformException(执行 setData 时出错,PERMISSION_DENIED:权限缺失或不足。,null)
- reactjs - React JS,当单击一个选项时,其他选项也被选中
- if-statement - 谷歌表中的计数
- java - 尝试使用“do -while”迭代特定间隔
- docker - docker容器重启后不工作
- c# - Infragistics Ultragrid - 选择最右边的列时不要移动到行下方
- javascript - 如何找到加载缓慢的 SAPUI5 应用程序的加载瓶颈