触发componentWillReceiveProps

时间:2018-01-17 19:15:08

标签: reactjs typescript redux react-router

我开始使用打字稿并对redux做出反应。我有一个登录组件,它反过来有它的动作创建者,它调度LOGIN_SUCCESS动作:

export const actionCreators = {
    loginRequest: (user:string): AppThunkAction<KnownAction> => (dispatch, getState) => {
         userService.login(JSON.parse(user))
         .then(
             (data)=>{//ok
                dispatch({ type: 'LOGIN_SUCCESS', success: true, message: data });    

            },
            (data)=>{//error
                toast.error(""+data)
            }
        );

        dispatch({ type: 'LOGIN_REQUEST' });
    },
...
};

然后在reducer上:

export const reducer: Reducer<LoginState> = (state: LoginState, action: KnownAction) => {
    switch (action.type) {
        case 'LOGIN_REQUEST':
            return {... state};
        case 'LOGIN_SUCCESS':
            return {... state ,success:action.success, message:action.message};
        case 'LOGIN_FAILURE':
            ...
        default:
            ...
    }

   ...
};

我正在更新州。然后我希望在组件中:

componentWillReceiveProps(newProps: LoginProps){
        console.log(newProps);
        if(newProps.success){
            this.props.history.push('/home')
        }
    }

它将收到新的道具并将我推送到/ home,但没有任何反应。我已经设置了一个console.log(newProps)来检查它何时获得了新属性,但它从来没有被攻击过。谁能帮我?任何帮助将不胜感激。

修改

这就是我将它们连接起来的方式:

export default connect(
    (state: ApplicationState) => state.login, // Selects which state properties are merged into the component's props
    loginState.actionCreators                 // Selects which action creators are merged into the component's props
  )(Login) as typeof Login;

2 个答案:

答案 0 :(得分:0)

您需要从connect

的第一个参数返回一个对象
export default connect(
    (state: ApplicationState) => ({signup: state.signup}), // Selects which state properties are merged into the component's props
    loginState.actionCreators                 // Selects which action creators are merged into the component's props
  )(Login) as typeof Login;

然后将其用作

componentWillReceiveProps(newProps: LoginProps){
    console.log(newProps);
    if(newProps.signup.success){
        this.props.history.push('/home')
    }
}

假设路径道具可供组件使用,如果没有,请检查 this

答案 1 :(得分:0)

<Redirect />合并到Redux商店的道具signup.success时,替代选项会改为使用 react-router-dom true重定向到“/ home” 1}} / truthy:

{this.props.signup && this.props.signup.success &&
    <Redirect to="/home" />
}

当您的Login组件连接到Redux商店时,您只需监听/观看mapStateToProps值,而不需要Component生命周期挂钩。

如果您确实使用了这种方法,则可能需要将连接的Login组件用withRouter包裹起来:

export default withRouter(connect(
    (state: ApplicationState) => ({signup: state.signup}), 
    loginState.actionCreators
  )(Login)) as typeof Login;

希望这有帮助。

谢谢!