reactjs - 条件渲染然后清除状态(警告/错误)
问题描述
在我的componentDidMount
中,我正在获取数据,然后setState
用于存储该数据。在我的render
中,我根据我的状态有条件地渲染/重定向到一个组件,但是我需要清除我的状态,以免它陷入无限的重定向循环。但是,当我在我的 中调用该函数进行重定向时render
,我收到了一个警告Cannot update during an existing state transition (such as within render)
。我应该如何解决这个问题?
componentDidMount() {
let branchKeyTest = 'key_test_b'
branch.init(branchKeyTest, (err, data) => {
this.setState({ redirectPath: data })
}
this.setState({ isLoading: false })
})
redirectToPath = (path) => {
const { history } = this.props;
history.push(path);
this.setState({ redirectPath: null })
}
render() {
const { isLoading, redirectPath } = this.state;
const { token, location } = this.props;
const loggedIn = !!token;
if (!isLoading && loggedIn && (redirectPath != null)) {
switch (redirectPath.link_type) {
case 'new_release':
this.redirectToPath(`/releases/releaseinfo/${redirectPath.id}`)
break;
default:
return;
}
}
if (!isLoading) {
return (
<div>Done Loading</div>
);
}
else {
return (<h1>Loading...</h1>)
}
}
解决方案
推荐阅读
- javascript - Django/Plotly - 带有 JS 的点击事件
- oracle - 通过使用 Oracle 的 Join 获取每个状态的 Store 计数
- cmake - How to print without newline in CMake?
- javascript - 根据我的下拉选择在我的文本框中填充 Db 值
- python - UnicodeDecodeError:“ascii”编解码器无法解码位置 1039 中的字节 0x92:序数不在范围内(128)
- webpack - Webpack 供应商块太大
- ms-access - 访问数据库查询以将由“,”分隔的列拆分为多行
- scala - 如何以纯 FP 方式设计有状态的 Actor
- html - 在 asp.net 中的相同 div 中迭代循环
- apache-kafka-streams - Materialized<> 类型中的 withValueSerde() 方法不适用