我正在使用来自react-router-dom v4的Redirect重新加载组件,当组件首次加载时,api调用发生在ComponentDidMount中。但是,当通过Redirect触发组件重载时,此方法不会运行。
我有一个名为TopicList的组件,它由react-router-dom中的Route路径/topic显示。
PostTopic是一个模态框,在TopicList中呈现。在PostTopic内部,我添加了一个称为redirect的属性到状态中,并使用它来渲染到to="/topic"的Redirect组件。在将一些数据发布到api后,我进行重定向。
在TopicList中,当通过Redirect重新加载时,componentDidMount()不会运行,因此无法进行新发布数据的api调用。
最好的方法是什么,在通过React路由器从Redirect重新加载相同的路由之后,重新获取api调用的数据?
我有一个名为TopicList的组件,它由react-router-dom中的Route路径/topic显示。
PostTopic是一个模态框,在TopicList中呈现。在PostTopic内部,我添加了一个称为redirect的属性到状态中,并使用它来渲染到to="/topic"的Redirect组件。在将一些数据发布到api后,我进行重定向。
在TopicList中,当通过Redirect重新加载时,componentDidMount()不会运行,因此无法进行新发布数据的api调用。
最好的方法是什么,在通过React路由器从Redirect重新加载相同的路由之后,重新获取api调用的数据?
class PostTopic extends Component
state = {
redirect: false
}
handleSubmit = (e) => {
e.preventDefault();
const { body, subject } = this.state;
api.postTopic(this.props.store.token,subject,body)
.then( response => {
this.setState({redirect:true})
})
.catch( error => {
this.setState({error});
});
}
renderRedirect = () => {
if(this.state.redirect){
return <Redirect to={this.props.currentPath}/>
}
}
render(){
return(
...
...
...
{this.renderRedirect()}
}
}