useState object set

前端 未结 3 1871
灰色年华
灰色年华 2021-01-28 17:32

I am new to ReactJS and working with Hooks. I want to set state for object. Here is my code:

const StartPage = (props)=> {
    const [user,setUser] = useState         


        
相关标签:
3条回答
  • 2021-01-28 18:10

    setInfo is asynchronous and you won't see the updated state until the next render, so when you do this:

    if(data!==undefined){
      setInfo({...info, data })
    }
    console.log(info)
    

    you will see info before the state was updated.

    You can use useEffect hook (which tells React that your component needs to do something after render) to see the new value of info:

    const StartPage = props => {
      const [user, setUser] = useState('');
      ...
      useEffect(() => {
        console.log(info);
      }, [info]);
      ...
    }
    

    EDIT

    Also as others have pointed out, you likely want to destructure data when setting the state: setInfo({...info, ...data }) (this entirely depends on how you are planning to use it), otherwise the state will look like this:

    {
      email: ...
      data: ...
    }
    
    0 讨论(0)
  • 2021-01-28 18:14

    What is the structure of data received from the api call? you can try setting it like so -

    setInfo({ ...info, email: data.email })
    
    
    0 讨论(0)
  • 2021-01-28 18:17

    I'm not exactly sure what you mean by "not working" but it looks like you are deconstructing info but not data. My suspicion is that it is setting state but not the way you want. If data is an object with email as a property you most likely will want to deconstruct that too like this:

    setInfo({...info, ...data})
    

    You can use useEffect to console.log state changes if you want with something like this:

    import React, { useState, useEffect } from 'react'
    
    const StartPage = props => {
      const [info,setInfo] = useState({ email:'' })
      useEffect(() => {
        console.log(info)
      }, [info])
    
    0 讨论(0)
提交回复
热议问题