reactjs - 在 componentDidMount 中发出 http 请求并在那里更改状态,但它不会重新渲染我的 DOM,这有条件地取决于状态
问题描述
由于不推荐使用 componentWillMount(),我在 componentDidMount() 中发出 HTTP 请求并根据响应更新那里的状态。虽然 componentDidMount() 在 render() 方法之后运行,但是在 componentDidMount 中使用 this.setState() 应该再次调用 render 方法。因此,如果请求中存在某些错误,则应重新渲染有条件地取决于状态中错误属性的模态组件。但是状态没有改变,因此我的 Modal 组件永远不会被渲染。有人可以帮忙吗??
const withErrorHandler = (WrappedComponent, axios) => {
return class extends Component {
state = {
error: null
}
componentDidMount () {
axios.interceptors.request.use(req => {
this.setState({
error: null
});
return req;
});
axios.interceptors.response.use(res => res, error => {
this.setState({
error: error
});
});
}
errorConfirmedHandler = () => {
this.setState({
error: null
});
}
render() {
return (
<Aux>
<Modal show={this.state.error} modalClosed={this.errorConfirmedHandler}>
{this.state.error ? this.state.error.message : null}
</Modal>
<WrappedComponent {...this.props} />
</Aux>
);
}
}
}
解决方案
推荐阅读
- docker - Docker 启动 sonarqube:7.5-community 失败并获得 es 日志权限
- android - 为什么我无法在 Android 的 TabLayout 上更改或滑动标签?
- xamarin - 如何选择在 Android SDK 构建工具上安装哪些
- windows - 有没有办法跟踪任何 Windows 应用程序在 Windows 中执行的命令
- c - 我正在尝试增加一个 ID,但由于某种原因,它在设置第一个 ID 后不断重置
- oracle - 两个循环执行,第二个不能执行
- cron - Azure Web 作业在提供的 cron 模式上运行多次
- c# - C# 双精度减法应该 = 0
- c# - 设置 GameObject 位置会使 Unity 崩溃
- rust - 如果缺少 include_bytes!(...) 目标,则回退到替代值