带有useState的React Async示例未按预期运行,出了什么问题?

问题描述 投票:0回答:1

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

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个回答
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
    )
}
© www.soinside.com 2019 - 2024. All rights reserved.