简体   繁体   中英

New to React Hook, Why is state undefined after use once?

I have a question regarding how state is declared in react hook.

 const [ state, setState ] = useState({
        date: new Date(),
    })

 const { date } = state;

vs

const [ date, setDate ] = useState(new Date());

when date is called inside return, say

 return (
  <div>
    {date}
  </div>
)

console.log returns the current date, then undefined for the initial declaration, while the latter, the state persists.

Aren't these declarations the same? Why does the initial state persist only once?

In the statement const [ date, setDate ] = useState(new Date()); date = current date, so you can access it as {date}

In the statement const [ state, setState ] = useState({ date: new Date(), }) state is an object with key value pairs as date and new Date() respectively. Hence you need to use {state.date} in order to access date.

PLease accept this as answer, if you this helps you out.

I am not clear about the question you told since this is kind of unexpected behaviour. I have added some code here .

import React, {useState} from 'react';
import { render } from 'react-dom';

const WithStateObject = () => {
    const [state] = useState({ date: new Date() });
    return <div>{state.date.toString()}</div>;
}

const WithStateAttr = () => {
    const [date] = useState(new Date());
    return <div>{date.toString()}</div>;
}

const App = () => {
    return <div>
        <div>With State Object <WithStateObject /></div>
        <div>With State attribute <WithStateAttr /></div>

        <h2>Second Time</h2>

        <div>With State Object <WithStateObject /></div>
        <div>With State attribute <WithStateAttr /></div>
     </div>;
}

render(<App />, document.getElementById('root'));

You can check your code with this one. I have added the same component two time just to explain there is no connection between each component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM