Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 从状态创建对象_Reactjs_React Hooks - Fatal编程技术网

Reactjs 从状态创建对象

Reactjs 从状态创建对象,reactjs,react-hooks,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 w

我有两种状态:

  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.
我希望将这两种状态组合成一个对象,如下所示:

  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.
然后,我将对象作为道具发送到子组件,该道具稍后用于显示


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

它们是不同的选项

1。使用useState挂钩

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)

您只需在useState方法中创建一个对象作为参数,如下所示:

const [user, setUser] = useState({});
setUser(prevState => {
   return {...prevState, [user.firstState]: 6.5}
}
然后像这样调用
setUser
方法:

const [user, setUser] = useState({});
setUser(prevState => {
   return {...prevState, [user.firstState]: 6.5}
}
在此处阅读有关useState钩子的更多信息:

为什么?你为什么要这么做?为什么不在一个useState中使用两个变量并将其传递给
ChildComponent
可能更适合您您您可以将其创建为一个对象,使其成为useState({firstState:6.5,secondState:3.5});稍后将其用作简单的js对象,但我仍然可以更新状态吗@Freestyle09@ArastoSahbaei是的,您仍然可以像
setObject({…myObject,firstState:20})一样更新状态。
这将只更改对象的firstState部分