0

class组件自动合并:

...
state={age:22,name:'A'}
changeAge=()=>{
this.setState({age:25})
}
...

hooks:

cosnt Example=(props)=>{
const [person,setPerson]=useState({age:12,name:'A',id:000001})
const changAge=()=>{setPerson({age:25,name:'A',id:000001})}//hooks更新state方法
return ...
}

当然可以创建多个useState,如果向上述例子创建单useState多个state怎样实现合并更新, 试了Object.assign(person,{age:25}) setPerson(person)不起作用.

小木 230
3 天前提问
2 个回答
1

已采纳

useState本身是不支持像setState一样的浅拷贝的。但是可以封装一下:

思路如下:

const [person, setPerson] = useState({age:12,name:'A',id:000001})

const changeAge = (age) => {
  setPerson(prevPerson => ({...prevPerson, age}))
}

那你可以封装成一个通用的hook:

function useSetState(initial = {}) {
  const [state, saveState] = useState(initial)
  const setState = useCallback((newState) => {
    saveState(prev => ({...prev, ...newState}))
  }, [])

  return [state, setState]
}

使用:

const [person, setPerson] = useSetState({age:12,name:'A',id:000001})

const changeAge = (age) => {
  setPerson({age})
}

另外如果状态比较复杂,推荐使用useReducer

0

useReducer

撰写答案

推广链接