首页 > 解决方案 > 从状态创建对象

问题描述

我有两种状态:

  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}/>

将状态组合成一个对象的最佳实践是什么?

标签: reactjsreact-hooks

解决方案


他们是不同的选择

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);


推荐阅读