useState object set

前端 未结 3 1902
灰色年华
灰色年华 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: ...
    }
    

提交回复
热议问题