2017-08-11 68 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
}' –