Javascript 如何在componentWillReceiveProps中触发页面重定向?

Javascript 如何在componentWillReceiveProps中触发页面重定向?,javascript,reactjs,redux,react-router,react-redux,Javascript,Reactjs,Redux,React Router,React Redux,我的页面/组件输出一个表单,该表单在提交时调用我的后端API。如果成功,它将返回一个我添加到redux存储的对象 我使用componentWillReceiveProps,以便在我的组件中知道reducer是否成功地将对象添加到我的存储的属性中。我包括从redux路由器重定向 import { Redirect } from 'react-router-dom'; componentWillReceiveProps(nextProps) { if( nextProps.user.ac

我的页面/组件输出一个表单,该表单在提交时调用我的后端API。如果成功,它将返回一个我添加到redux存储的对象

我使用
componentWillReceiveProps
,以便在我的组件中知道reducer是否成功地将对象添加到我的存储的属性中。我包括从redux路由器重定向

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...
    }
}
从'react router dom'导入{Redirect};
组件将接收道具(下一步){
if(nextrops.user.activeSubscriptions){
this.props.user.activeSubscriptions=nextrops.user.activeSubscriptions;
}
if(Object.keys(nextrops.user.properties).length!=Object.keys(this.props.user.properties).length){
console.log(“let redirect..”;//这很有效
return();//这不。。。
}
}

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

您可以使用
窗口。location='/account/properties'在那里,而不是
return();//这不会…。

另一种方法是向默认状态添加一个额外属性,如下所示:

this.state = { userChanged: false };
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
        this.setState({userChanged: true});
    }
}
如果该情况有效,您需要在componentWillReceiveProps上添加一个setState,以便React知道它应该再次触发render方法,如下所示:

this.state = { userChanged: false };
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
        this.setState({userChanged: true});
    }
}
然后在渲染方法上:

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

}
render(){
if(this.state.userChanged){
返回();
}
//你的其他代码在这里。。。
}

它确实有效,但它会重新加载整个页面以转到该URL(如果这是唯一的解决方案,这很好……但它是吗?)我将添加一种新方法。或者您也可以转到
this.rekt='account/propertiesrender(){return{this.rekt&&}…more stuff}
@Martin中,它会起作用,因为你刚刚得到了道具。渲染周期将以任何方式进行完美-与您的完整解决方案一起工作,无需重定向。谢谢标记为答案!