【问题标题】:React Async example with useState not working as expected, what is the problem?使用 useState 的 React Async 示例未按预期工作,有什么问题?
【发布时间】:2020-08-17 12:21:19
【问题描述】:

React 对我来说是超级新的,并且学习了一些异步概念。目前,有我注释掉的工作代码。您可以看到工作代码采用useState(0)。 0 作为值,而没有工作的 useState 接受一个对象,useState({ counter: 0})。为什么它给我一个错误并输出 [object Object]1 和 NaN 而不是 number 预期的数字输出?

import React, { useState } from 'react'

const Async = () => {
    const [currentState, setState] = useState({
        counter: 0
    });

// Can we have prevCounter as an argument? 
// *The two methods below are incorrect!*

const increase = () => {
    setTimeout(
        () => setState((prevCounter) => ({
            counter: prevCounter + 1
        })
        ), 500
    );
} // will output [object Object]1

const decrease = () => {
    setTimeout(
        () => setState((prevCounter) => ({
            counter: prevCounter - 1
        })
        ), 500
    )
} // will output NaN

// This portion works fine. Above does not.
/* const [currentState, setState] = useState(0);

const increase = () => {
    setTimeout(
        () => setState(prevCounter => prevCounter + 1)
        , 500
    );
}

const decrease = () => {
    setTimeout(
        () => setState(prevCounter => prevCounter - 1)
        , 500
    );
} */

return(
    <div>
        <h1>{currentState.counter}</h1>  
        {console.log(currentState.counter)}
        <button onClick={increase}>Increase</button>
        <button onClick={decrease}>Decrease</button>
    </div>  
  );
}

export default Async;

【问题讨论】:

    标签: reactjs function asynchronous callback state


    【解决方案1】:

    需要正确访问状态对象counter 属性currentState.counter,或者在本例中为prevCounter.counter,因为这是您在功能状态更新中命名的先前状态对象。

    prevCounter 是一个对象,因此当您对其应用算术运算时,结果应该是预期的NaN

    const increase = () => {
        setTimeout(
            () => setState((prevCounter) => ({
                counter: prevCounter.counter + 1
            })
            ), 500
        );
    } // will output [object Object]1
    
    const decrease = () => {
        setTimeout(
            () => setState((prevCounter) => ({
                counter: prevCounter.counter - 1
            })
            ), 500
        )
    }
    

    【讨论】:

    • 德鲁,谢谢。我快疯了,我知道我走在正确的道路上,我从来不知道如果你将某些东西作为参数传入,它也会是一个对象。
    猜你喜欢
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 2022-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多