首页 > 解决方案 > 数组填充异步?(反应功能意外)

问题描述

我有一个结构如下的 React 组件:

class SearchElement extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            otherArray: [],
            testArray: [],
        }
        this.handleClick = this.handleClick.bind(this);
    }

    otherEvent = (event) => {
        this.setState( { otherArray:event.target.value }, this.handleClick);
    }
    
    handleClick() {
        const { otherArray } = this.state;
        var exampleArray = [];
        console.log("THIS SHOULD BE EMPTY");
        console.log(exampleArray);
        console.log("exampleArray already has elements in it");
        //...
        //changes made to exampleArray
        this.setState({ testArray: exampleArray });
    }

通过单击 HTML 按钮调用 otherEvent,然后该按钮应调用 handleClick 作为 setState 调用中的回调函数。然而,当打印语句显示 exampleArray 不知何故已经有元素(而且它也不是正确的元素)。如果相关,我正在使用 NextJS。我假设我对异步调用或如何维护 React 状态感到困惑。如果我应该提供更多信息,请告诉我。

谢谢!

标签: javascriptreactjsasynchronousstatenext.js

解决方案


推荐阅读