javascript - 在 React 中使用数组设置状态

标签 javascript arrays reactjs setstate

我正在尝试用 React 中使用 setState 的函数生成的数组替换最初为空的数组。我的构造函数中有如下内容:

this.state = {
    sources: []
};

这显示了正确的数组(我用 [0,1,2] 测试了它)。但是,当我尝试以这样的方法设置状态时:

this.setState({
    sources: [0,1,2]
})

它不起作用并且仍然显示空(或原始)数组。我知道你不能直接在 React 中改变数组作为状态,但我不认为这就是我在这里所做的。以下是我在研究这个问题时尝试过的其他一些方法,但都没有奏效:

this.setState({
    sources: [...this.state.sources, 1]
})

...

this.setState({
    sources: this.state.sources.concat('test')
})

...

var temp = [0,1,2]
this.setState({
    sources: temp
})

在此先感谢您的帮助!

编辑完整代码:

export class SrcMenu extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            sources: [],
        };

        this.searchSources = this.searchSources.bind(this);
    }

    searchSources() {
    // commented out the actual method to replace with test code
        var temp=[0,1,2];
        console.log(temp); // [0,1,2] so I know the method works
        this.setState({
            sources: temp // etc for the other things i tried
        })
        console.log("this.state.sources: " + this.state.sources); // empty
    }

    render() {
        return(
        // etc...
          <button type="button" onClick={this.searchSources}>Test</button>
        );
    }
}

最佳答案

您的代码可以正常工作,但您没有考虑到 setState 是异步的。如果您在可以作为 setState 的第二个参数的回调中记录 this.state,它将保证它已更新。

this.setState({ sources: temp }, () => {
  console.log(this.state.sources);
});

关于javascript - 在 React 中使用数组设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51383597/

相关文章:

javascript - 插画家 Javascript : Select Based on Swatch

javascript - 如何为数组中的每 6 个项目添加一个升序数字?

reactjs - 如何在 Next.JS 14 的服务器中实现 useEffect?

reactjs - 如何在单击时惯用地将文本组件转换为输入组件?

reactjs - react native TabNavigator 不显示

javascript - 如何暂停用 js 和 html5 制作的简单 Canvas 游戏?

javascript - aria-owns、aria-invalid、aria-expanded的解释和示例

javascript - backbone.js 复杂模型

c - 指向位数组的指针数组

c - c中函数调用中指向数组的指针