簡體   English   中英

如何在 React Native 中使用 redux 在 props 中定義變量/方法

[英]How to define a variable/method in the props with redux in React Native

我正在實施身份驗證,道具有問題。

當我顯示道具時,我沒有道具authState所以我得到一個錯誤,我不明白它來自哪里,我無法解決它。 這是錯誤:

[21:42:10] TypeError: undefined is not an object (evaluating '_this$props$authState.app_started')

This error is located at:
    in App (at withExpoRoot.js:22)
    in RootErrorBoundary (at withExpoRoot.js:21)
    in ExpoRootComponent (at renderApplication.js:34)
    in RCTView (at View.js:44)
    in RCTView (at View.js:44)
    in AppContainer (at renderApplication.js:33)

應用程序.js

import ... 

export default class App extends React.Component {

  componentDidMount() {
    this.props.checkLogin();
  }
  _renderSplash = ()=>{
    return (
        <View>
          <ActivityIndicator size="large"/>
          <Text children='Loading...'/>
        </View>
    );
  }

  _renderRoot = (authenticated)=>{
    const Navigation = Navigation(authenticated);
    return <Navigation/>;
  }

  render() {
      console.log(this.props); // it don't show -> this.props.authState
      const {app_started, authenticated} = this.props.authState;
      const Root = connect(mapStateToProps, mapDispatchToProps) ((app_started ? this._renderRoot(authenticated): this._renderSplash));
      return (
        <Provider store={configureStore}>
          <Root/>
        </Provider>
      );
  }

}
const mapStateToProps = (state) => {
      return {
        authState: state.authState
      }
};
const mapDispatchToProps = (dispatch, ownProps)=>{
  return {
    async checkLogin(){
      const isLoggin = await AsyncStorage.getItem('authenticated').catch(e => console.log(e));
      if(isLoggin){
        dispatch(actionCreator(LOGIN_SUCCESS))
      }
      dispatch(actionCreator(APP_LOADED))
    }
  }
};

配置Store.js

import {combineReducers, createStore} from 'redux';
import authStateReducer from './authStateReducer';

const rootReducer = combineReducers({
    authState: authStateReducer
});

const configureStore = () => {
    return createStore(rootReducer);
};

export default createStore(configureStore);

導航.js

import ...
const Navigation = (authenticated)=>createStackNavigator({
    login: {
        screen: Login,
        navigationOptions: {
            title: 'login'
        }
    },
    dashboard: {
        screen: Dashboard,
        navigationOptions: {
            title: 'dashboard'
        }
    }
}, {
    initialRouteName: authenticated ? 'dashboard': 'login'
});
export default Navigation;

authStateReducer.js

import ...
const authStateReducer = (state={app_started: false, authenticated: false} , action)=>{
    let next_state;
    switch (action.type) {
        case LOGIN_SUCCESS:
            next_state = {
                ...state, authenticated: true
            };
            return next_state;
        case LOGOUT:
            next_state = {
                ...state, authenticated: false
            };
            return next_state;
        case  APP_LOADED:
            next_state = {
                ...state, app_started: true
            };
            return next_state;
        default:
            return state;
    }
}

export default authStateReducer;

登錄.js

import ...
class Login extends React.PureComponent{
    _login = ()=>{
        // check the fields
        let token = 'whatever';
        this.props.authSuccess(token);
    };
    render() {
        return (
            <View>
                 <TextInput.../>
                 <TextInput...
                     onSubmitEditing={this._login}
                 />
                 <Button ... onPress={this._login}/>
            </View>
        );
    }
}

const mapStateToProps = (state) => {
    return state

};
export const actionCreator = (action, payload=null)=>{return{type: action, payload: payload}};

const mapDispatchToProps = (dispatch,ownProps)=>{
    return {
        authSuccess: (token)=>{
            AsyncStorage.multiSet([['token',token], ["login", '1']]);
            dispatch(actionCreator(LOGIN_SUCCESS))
        }
    }
};

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

我發現了錯誤,它在configureStore.js

一個輕量級的 React-Native Redux 樣板,可以使用現代技術。 這個 Repo 為你的下一個 React-Native 項目提供了一個良好的開端。 請檢查鏈接

https://github.com/Anyline/react-native-redux-boilerplate

在 App.js 中authState是未定義的,因為你需要連接你的mapStateToPropsmapDispatchToProps否則它在 this.props 中都不可用。

它應該看起來像:

應用程序.js

import...
import { connect } from 'react-redux';

class App extends React.Component { // <- get rid of export default here
...

// after mapStateToProps and mapDispatchToProps
export default connect(mapStateToProps, mapDispatchToProps)(App);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM