React Native:未调用componentWillUpdate

时间:2018-03-14 21:02:50

标签: reactjs react-native redux react-navigation

我正在使用React Navigation和Redux创建React Native应用。

class LoginScreen extends Component {

state = {
    email: '',
    password: '',
    errors: {
        email: '',
        password: ''
    }
}

onPressLogin() {
    this.props.signIn(this.state.email, this.state.password);
}

componentWillUpdate(nextProps, nextState) {
    console.log("component will update");

    if (nextProps.signedIn) {
        this.props.navigation.navigate('LoggedIn');
    }
}

render() {
    if (this.props.signedIn) {
        this.props.navigation.navigate('LoggedIn');
    }

    return(<View>...</View);

this.props.signIn()是一个Redux动作,现在只是更新状态:{signedIn:true}。下面的代码是我传递Redux操作和状态为props的地方。

function mapStateToProps(state, props) {
    return {
        signedIn: state.authReducer.signedIn,
    }
}

function mapDispatchToProps(dispatch) {
    return bindActionCreators(Actions, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(LoginScreen);

当触发动作时,状态会按照我的预期更新并调用render()。如果我将导航代码放在render()函数中,一切正常。为了使代码更清晰,我想将它移动到componentWillUpdate()中,但是这个函数没有触发。控制台日志永远不会打印到控制台。

这是我的动作和减速器。

动作:

export const SIGN_IN_SUCCESS = 'SIGN_IN_SUCCESS';
export const SIGN_IN_FAIL = 'SIGN_IN_FAIL';

 export function signIn(email, password) {

     return (dispatch) => {
         dispatch({ type: SIGN_IN_SUCCESS });
     }
 }

减速机:

import { combineReducers } from 'redux';

import {
    SIGN_IN_FAIL,
    SIGN_IN_SUCCESS
} from '../actions/';

let authState = { signedIn: false, error: '' }


const authReducer = (state = authState, action) => {
    switch(action.type) {
        case SIGN_IN_SUCCESS:
            return {...state, signedIn: true }
        case SIGN_IN_FAIL:
            return {...state, signedIn: false, error: action.error }
        default:
            return state;
    }
}

const rootReducer = combineReducers({
    authReducer
});

export default rootReducer;

1 个答案:

答案 0 :(得分:0)

因为您在render()函数内执行了导航:

render() {
    if (this.props.signedIn) {
        this.props.navigation.navigate('LoggedIn');
    }

    return(<View>...</View);
}

必须是:

render() {
    return !this.props.signedIn && (<View>...</View);
}