【问题标题】:setState not working inside a simple if condition of a functionsetState 在函数的简单 if 条件中不起作用
【发布时间】:2021-11-10 19:25:31
【问题描述】:

我正在尝试在 if 条件内的函数中设置状态,但你的值没有得到更新。

请在下面找到代码sn-p

archivePath = (filepath: string) => {
        if (filepath) {
            const breadcrumbs: any[] = [];
            var selectedgroup: string | undefined = "";
            let relPath: string = this.props.selectedGroup + "";
            breadcrumbs.push({ name: this.props.selectedGroup, path: relPath });
            const sliceCount = relPath.split("/").length;
            const pathMap = filepath.split("/").slice(sliceCount);
            if (pathMap.length > 0) {
                console.log("inside if of pathMap");
                selectedgroup = pathMap.pop();
                console.log("selectedgroup: ", selectedgroup);
                this.setState({
                    selectedFolder: selectedgroup
                }, () => {
                    console.log("selectedFolder in enterfolder: ", this.state.selectedFolder);
                });
            }
            else {
                this.setState({
                    selectedFolder: '',
                })
            }
            pathMap.map((baseName) => {
                console.log("baseName in enterfolder: ", baseName);
                relPath += ("/" + baseName);
                if (baseName === ".archive" || baseName.startsWith(".")) {
                    // this.setState({ isArchive: true });
                } else {
                    breadcrumbs.push({ name: baseName, path: relPath });
                }
            });
           

控制台日志为创建的选定组的局部变量打印正确的值,但 setState 没有更新状态值

【问题讨论】:

  • 你如何确定 setState 没有更新状态值?
  • console.log("selectedFolder in enterfolder:", this.state.selectedFolder);这个控制台日志没有显示正确的值
  • 虽然这正是 setState 应该解决的问题,但为了确认,您可以在 console.log("selectedFolder in enterfolder:", this.state 之前等待 2 秒吗? .selectedFolder);看看是否是状态传播问题?

标签: reactjs state setstate


【解决方案1】:

正如@RaoVirinchi 提到的,可以将回调函数传递给this.setState 方法。

this.setState 以异步方式更新状态。因此,状态更新不会立即可见。因此,请保持如下,并在 render 方法中单独进行控制台日志,以确保它捕获正确的状态更新。

this.setState({
  selectedFolder: selectedgroup,
});

在组件渲染方法中包含控制台日志。然后它会在组件重新渲染状态更新时记录更新的状态。

console.log("selectedFolder in enterfolder: ", this.state.selectedFolder);

【讨论】:

  • 其实可以给setState传一个回调。它应该在状态传播完成并重新渲染组件后执行。请参考stackoverflow.com/questions/37401635/…
  • 明白你的意思。这是可能的。我会更新答案。
  • 谢谢大家的帮助!我能够通过在 componentDidMount() 中设置状态来解决问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-31
  • 1970-01-01
  • 2017-04-24
  • 1970-01-01
  • 1970-01-01
  • 2020-11-16
  • 1970-01-01
相关资源
最近更新 更多