首页 > 解决方案 > 当我需要进行大量计算时优化代码反应

问题描述

我在 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>
     )

像上面那样处理代码是一种好方法吗?

标签: react-hooks

解决方案


在你的情况下,最好使用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();
  }
}

推荐阅读