简体   繁体   English

React Hook 新手,为什么使用一次后状态未定义?

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

I have a question regarding how state is declared in react hook.我有一个关于如何在 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当 date 在 return 中被调用时,说

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

console.log returns the current date, then undefined for the initial declaration, while the latter, the state persists. console.log 返回当前日期,然后为初始声明未定义,而后者则状态保持不变。

Aren't these declarations the same?这些声明不一样吗? Why does the initial state persist only once?为什么初始状态只持续一次?

In the statement const [ date, setDate ] = useState(new Date());在语句const [ date, setDate ] = useState(new Date()); date = current date, so you can access it as {date} date = 当前日期,因此您可以将其作为 {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.在语句const [ state, setState ] = useState({ date: new Date(), }) state 是一个对象,键值对分别为 date 和 new Date() 。 Hence you need to use {state.date} in order to access date.因此您需要使用 {state.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.我添加了两次相同的组件只是为了说明每个组件之间没有联系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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