使用redux

时间:2018-03-27 09:29:52

标签: react-native redux react-navigation

我在登录时遇到问题我的重定向没有完成,我使用后面的铁路API,我可以恢复用户,但是当我点击登录时页面重新加载并且不在主屏幕上导航。 / p>

在我的AuthActions.js发送后我添加了NavigationActions.navigate(' Home'),这应该允许我转到主页

AppNavigator.js

import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { addNavigationHelpers, StackNavigator, TabNavigator } from 'react-navigation';

import { addListener } from '../../utils/redux';


import LoginScreen from '../login/LoginForm';
import RegisterScreen from '../register/RegisterForm';
import LogoutScreen from '../logout/Logout';
import Home from '../home/HomeList';
import Hair from '../hair/HairList';

export const Tabs = TabNavigator({
  screen1: {
    screen: Home
  }
});

export const AppNavigator = StackNavigator({
  Login: { screen: LoginScreen },
  Main: { screen: Home },
  Hair: { screen: Hair },
},{
  initialRouteName : 'Login'
});


class AppWithNavigationState extends React.Component {
  static propTypes = {
    dispatch: PropTypes.func.isRequired,
    nav: PropTypes.object.isRequired,
  };

  render() {
    const { dispatch, nav } = this.props;
    return (
      <AppNavigator
        navigation={addNavigationHelpers({
          dispatch,
          state: nav,
          addListener,
        })}
      />
    );
  }
}

const mapStateToProps = state => ({
  nav: state.nav,
});

export default connect(mapStateToProps)(AppWithNavigationState);

AuthReducers.js

import {
  EMAIL_CHANGED,
  PASSWORD_CHANGED,
  LOGIN_USER_SUCCESS,
  LOGIN_USER_FAIL,
  LOGIN_USER
 } from '../actions/types';

const INITIAL_STATE = {
  email: '',
  password: '',
  user: null,
  error: '',
  loading: false,
 };

export default (state = INITIAL_STATE, action) => {
  // console.log('action =>', action);
  switch (action.type) {
    case EMAIL_CHANGED:
      return { ...state, email: action.payload };
    case PASSWORD_CHANGED:
      return { ...state, password: action.payload };
    case LOGIN_USER:
      return { ...state, loading: true, error: '' };
    case LOGIN_USER_SUCCESS:
      return { ...state, ...INITIAL_STATE, user: action.payload };
    case LOGIN_USER_FAIL:
      return { ...state, error: 'Authentication Failed.', password: '', loading: false };
    default:
      return state;
  }
};

// newState === oldState ? nothing : update state, so component too

AuthActions.js

import { NavigationActions } from 'react-navigation';
import Api from '../api';
import User from '../models/User';

import {
  EMAIL_CHANGED,
  PASSWORD_CHANGED,
  LOGIN_USER_SUCCESS,
  LOGIN_USER_FAIL,
  LOGIN_USER
 } from './types';

export const emailChanged = (text) => {
  return {
    type: EMAIL_CHANGED,
    payload: text
  };
};

export const passwordChanged = (text) => {
  return {
    type: PASSWORD_CHANGED,
    payload: text
  };
};

export const loginUser = ({ email, password }) => {
  return (dispatch) => {
    dispatch({ type: LOGIN_USER });
    Api.userSignUp(email, password)
      .then((user) => loginUserSuccess(dispatch, user))
      .catch((error) => {
        console.log(error);
        loginUserFail(dispatch);
      });
  };
};

const loginUserFail = (dispatch) => {
  dispatch({
    type: LOGIN_USER_FAIL
  });
};

const loginUserSuccess = (dispatch, user) => {
  // console.log('access token =>', User.getAccessToken());
  // Api.createEmployee(null);
  dispatch({
    type: LOGIN_USER_SUCCESS,
    payload: user,
  });
  NavigationActions.navigate('home'); //HERE NOT REDIRECT AFTER SUCCESS TO HOME 

};

LoginForm.js

import React, { Component } from 'react';
import { Text } from 'react-native';
import { connect } from 'react-redux';
import { emailChanged, passwordChanged, loginUser } from '../../actions';
import { Card, CardSection, Input, Button, Spinner } from '../common';

class LoginForm extends Component {
  onEmailChange(text) {
    this.props.emailChanged(text);
  }

  onPasswordChange(text) {
    this.props.passwordChanged(text);
  }

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

    this.props.loginUser({ email, password });
  }

  renderButton() {
    if (this.props.loading) {
      return <Spinner size="large" />;
    }

    return (
      <Button onPress={this.onButtonPress.bind(this)}>
        Login
      </Button>
    );
  }

  render() {
    return (
      <Card>
        <CardSection>
          <Input
            label="Email"
            placeholder="email@gmail.com"
            onChangeText={this.onEmailChange.bind(this)}
            value={this.props.email}
          />
        </CardSection>

        <CardSection>
          <Input
            secureTextEntry
            label="Password"
            placeholder="password"
            onChangeText={this.onPasswordChange.bind(this)}
            value={this.props.password}
          />
        </CardSection>

        <Text style={styles.errorTextStyle}>
          {this.props.error}
        </Text>

        <CardSection>
          {this.renderButton()}
        </CardSection>
      </Card>
    );
  }
}

const styles = {
  errorTextStyle: {
    fontSize: 20,
    alignSelf: 'center',
    color: 'red'
  }
};

const mapStateToProps = ({ auth }) => {
  const { email, password, error, loading } = auth;

  return { email, password, error, loading };
};

export default connect(mapStateToProps, {
  emailChanged, passwordChanged, loginUser
})(LoginForm);

App.js

import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxThunk from 'redux-thunk';
import AppReducer from './reducers';
import AppWithNavigationState from './components/navigator/AppNavigator';
import { middleware } from './utils/redux';
import User from './models/User.js';
import {
  NavigationActions,
} from 'react-navigation';


const store = createStore(
  AppReducer,
  applyMiddleware(ReduxThunk),
);

class App extends Component {
  state = { isLoggedIn: null }
  componentWillMount() {
    // Si le asyncstorage a changé (connexion, etc)
    User.getCurrent().then((user) => {
      console.log('GetCurrentUser =>', user);
      if (user) {
        this.setState({isLoggedIn: true});
        this.props.navigation.navigate('Main', user);
      }
      else {
        this.setState({isLoggedIn: false});
      }
    })
  }

  render() {
    return (
      <Provider store={store}>
        <AppWithNavigationState />
      </Provider>
    );
  }
}

export default App;

我担心有一天会担心,我仍然没有找到解决方案

2 个答案:

答案 0 :(得分:0)

使用此代码NavigationActions.NAVIGATE(“ home”)对我有用

答案 1 :(得分:0)

您必须像这样在您的家庭中使用componentWillReceiveProps:

//主页

componentWillReceiveProps(nextProps) {
   if(nextProps.user) {
     this.props.navigation.navigate('Home');
   }
}

LoginForm.js

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

您可以这样编辑AuthReducers.js:

 case LOGIN_USER_SUCCESS:
      return { ...state, ...INITIAL_STATE, user: action.user};

对我有用!