reactjs - React 的重定向组件在 axios .then() 承诺中没有按预期工作
问题描述
我有一个带有以下路由的反应路由器:
'/' = 我的主应用程序组件 '/create' = 我的辅助视图
在按钮 onClick 的 Create 视图中,我发出 axios.post 调用以将 JSON 对象发布到我们拥有的 API。
成功后,我使用 Reacts setState({ReturnToHome : true}) 设置了一个名为 ReturnToHome 的状态变量
在我的渲染方法中,我有一个:
if (this.state.ReturnToHome) { return ( <Redirect to='/' /> )};
重要提示:这是我正在努力解决的有趣问题:
1)当这个相同的 this.setState 调用不在 axios 承诺的 .then 中时,重定向工作完美 2)当 this.setState 在承诺的 .then 内时,它不起作用。
起初我认为这可能是一个范围问题,所以我将其保存到 pThis 并专门在 .then 中使用了 pThis,但它没有任何积极作用。
另请注意:当我第一次进入视图时,路径是:#/create。在我使用重定向更新状态后,路径是 ?#/create... 我不确定这是否相关,但希望它可能是一个线索。
关于为什么这不起作用的任何想法?甚至可能是如何在 Promise 类型的场景中完成的工作示例?
解决方案
- 确保您使用 React-router 组件包装了您的应用层次结构
<Switch>
并正确定义了您的路由,在可能的可用路径上进行切换迭代允许您使用路径变量处理错误。 - 最好使用
&&
标记在渲染中写入条件。例如:return (this.state.ReturnToHome && <Redirect to="/" />)
这将完成这项工作。
理论上,在每次状态更新时,组件都应该更新并且会更新并且最终会渲染,所以问题不在于渲染函数。
所以这是您的案例的一些示例:
export class App extends React.component {
.....
render() {
return <ReactRouter>
<Switch>
<Route exact path="/" render={homeComponent} />
<Route path="/create" render={createComponent}/></Switch>
</ReactRouter>
}
export class CreateComponent extends React.component {
constructor(){
this.state = {
ReturnToHome: false
}
this.callToApi = this.callToApi.bind(this)
}
callToApi = e => {//e not required but always good to record event handlers......
const self = this
axios.post("apiuri",{params}..complete the post method requiremnets based on api..).then((response)=> {
self.setState({ReturnToHome:true})
})
}
render(){
return ....some logic with buttons to start the callToApi method.....
(this.state.ReturnToHome && <Redirect to="/" />)
}
推荐阅读
- reactjs - react native 和 expo:发送日志消息的问题 symbolicatedStack
- java - How model circular dependency in dagger2?
- python - 如何比较python中的层次回归模型?
- google-data-studio - 数据工作室社区可视化产品部署未重新加载
- r - 为什么 adgenet 的 find.clusters 不起作用?
- android - 如何识别三角形上的触摸?
- kubernetes - 按主机名的 Gloo TCP 代理
- python - 错误:尝试在 GKE 上启动 Python 烧瓶应用程序时,“”不是有效的端口号
- reactjs - 如何在打字稿中使用数组作为参数?找不到名称“数组”(反应)
- bash - 当文件名中有空格时,无法对目录的内容进行分类