2017-08-11 27 views
2

我的页面/组件输出一个表单,在提交时调用我的后端API。如果成功,它会返回一个我添加到我的redux商店的对象。如何在componentWillReceiveProps中触发页面重定向?

我使用componentWillReceiveProps为了在我的组件中知道reducer是否成功地将对象添加到我的商店的属性。我包含了来自redux-router的Redirect。

import { Redirect } from 'react-router-dom'; 

componentWillReceiveProps(nextProps) { 

    if(nextProps.user.activeSubscriptions) { 
     this.props.user.activeSubscriptions = nextProps.user.activeSubscriptions; 
    } 

    if(Object.keys(nextProps.user.properties).length != Object.keys(this.props.user.properties).length) { 
     console.log("lets redirect.."); // this works 
     return (<Redirect to={"/account/properties"} />); // this doesn't... 
    } 
} 

如何在我的componentWillReceiveProps中的if()语句中触发重定向?

回答

2

您可以使用window.location='/account/properties';那里,而不是return (<Redirect to={"/account/properties"} />); // this doesn't...

另一种方法将是一个额外的属性添加到您的默认状态,这样的事情:

this.state = { userChanged: false }; 

你还需要添加componentWillReceiveProps上的setState如果该情况有效,则React知道它应该再次触发呈现方法,如下所示:

然后

上渲染方法:

render() { 
    if(this.state.userChanged) { 
     return (<Redirect to={"/account/properties"} />); 
    } 
// Your other code goes here... 

} 
+0

它的工作,但它重新加载整个页面去那个URL(这是好的,如果它是唯一的解决办法......但果真如此吗?) – Lazhar

+0

我来补充一种新的方法。 – Martin

+0

或者你可以去'this.rekt ='帐户/属性;'和在'渲染(){返回

{this.rekt && } ... more stuff
}' –