首页 > 解决方案 > 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 类型的场景中完成的工作示例?

标签: reactjsreact-router-dom

解决方案


  1. 确保您使用 React-router 组件包装了您的应用层次结构<Switch>并正确定义了您的路由,在可能的可用路径上进行切换迭代允许您使用路径变量处理错误。
  2. 最好使用&&标记在渲染中写入条件。例如: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="/" />)
}

推荐阅读