【发布时间】: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);看看是否是状态传播问题?