React Redux-未定义不是评估this.props.navigation.navigate

时间:2019-03-08 23:19:13

标签: reactjs react-native redux react-redux react-thunk

我是Redux的新手,我不理解以下设置有什么问题。我收到错误消息: TypeError:TypeError:undefined不是对象(正在评估'this.props.navigation.navigate')

对于操作,我具有登录功能:

export const loginWithEmail = ({email, password}) => async (dispatch) => {
    dispatch({type: "LOADING"})
    try {
        let user = await auth.signInWithEmailAndPassword(email, password);
        dispatch({type: "LOGIN_SUCCESS", payload: user})
    } catch (error) {
        dispatch({type: "LOGIN_FAILURE"})
    }
}

登录组件:

class Login extends Component {
  componentWillReceiveProps(nextProps) {
    if(!_.isEmpty(nextProps.user)) {
      this.props.navigation.navigate('Home');
    }
  }

  login() {
    const {email, password} = this.props;
    this.props.loginWithEmail({email, password});
  }

  render() {
    return (
      ...
    )
  }
}

const mapStateToProps = state => {
  return {
    email: state.auth.email,
    password: state.auth.password,
    error: state.auth.error,
    user: state.auth.user
  }
}

export default connect(mapStateToProps, {loginWithEmail})(Login);

在我的App.js中

const AuthStack = createStackNavigator({
  Login: { screen: Login }
});

const MainStack = createStackNavigator(
  {
    Home: { screen: 'Home' },
    Auth: AuthStack
  },
  {
    initialRouteName: 'Home'
  }
);

const AppContainer = createAppContainer(MainStack);

export default class App extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));
    return (
      <Provider store={store}>
        <AppContainer/>
      </Provider>
    );
  }
}

我也确实尝试过在另一个组件中使用Login组件,例如:

const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));
return (
...
    <Provider store={store}>
        <Login navigation={this.props.navigation}/>
    </Provider>

我的反应导航版本是3.2.1

更新:尝试遵循React Native: TypeError: undefined is not an object (evaluating 'this.props.navigation.navigate')中的解决方案,但未成功

1 个答案:

答案 0 :(得分:0)

这是因为您正在直接使用“登录”屏幕组件的另一个文件。

<Provider store={store}>
    <Login/>
</Provider>

如果您期望this.props.navigation有一个值,则不会。解决方案是删除Provider的其他用法。

您已经拥有的以下内容足以连接到Redux。

<Provider store={store}>
    <AppContainer/>
</Provider>