从状态创建对象

时间:2019-10-01 13:41:57

标签: reactjs react-hooks

我有两种状态:

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

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

2 个答案:

答案 0 :(得分:1)

他们是不同的选择

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

答案 1 :(得分:0)

您可以在useState方法中简单地创建一个对象作为参数,所以就像这样:

const [user, setUser] = useState({});

并像这样调用setUser方法:

setUser(prevState => {
   return {...prevState, [user.firstState]: 6.5}
}

在此处阅读有关useState挂钩的更多信息: https://pl.reactjs.org/docs/hooks-reference.html#usestate