如何使用react hook将我的所有状态数据仅获取一行代码?

我只是最近尝试使用react hook。

如果我扩展Componet,我将这样声明我的状态:

  constructor(props) {
    super(props);

    // dummy state
    this.state = {
      focus: false
      name: 'test'
      image: ''
      avatarSource: '',imageBase: 'sfsafsfasf',imageLoader: null,}

如果我想发送所有状态值,我将使用...this.state

就像:

sendStateFunction(...this.state);

如果我使用react hook,我会这样声明我的状态:

const test = () => {

  const [name,setName] = useState('');
  const [image,setImage] = useState('');
  const [sex,setSex] = useState(0); 
  const [id,setId] = useState('');
}

但是我不知道如何仅使用一行代码发送所有状态值:

sendStateFunction();  // What should I type the arguments ?
xiaofeiyaya 回答:如何使用react hook将我的所有状态数据仅获取一行代码?

通过反应,您可以使用多个带有钩子的子值来定义状态对象:

function DummyComponent(){
const [state,setState] = useState({ focus: false,name: 'test',image: '',avatarSource: '',imageBase: 'sfsafsfasf',imageLoader: null,})
// You can update it like that:
return <Button onClick={()=>setState(prevState=>{return {...prevState,newKey:1}})}>Click</Button>
}

或者您可以使用hook useReducer来使用reducer。 所有这些问题都在React钩子Documentation

中说明
本文链接:https://www.f2er.com/3153835.html

大家都在问