如何在 React Native 中使用 redux 在 props 中定义变量/方法

Posted

技术标签:

【中文标题】如何在 React Native 中使用 redux 在 props 中定义变量/方法【英文标题】:How to define a variable/method in the props with redux in React Native 【发布时间】:2019-06-20 22:06:32 【问题描述】:

我正在实施身份验证,道具有问题。

当我展示道具时,我没有道具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)

App.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))
    
  
;

configureStore.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)=>returntype: 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

【问题讨论】:

App.js里面console.log(this.props)有dispatch方法吗? @PredragBeocanin,不,我没有。我试图将调度方法放在App.js,但我有同样的错误 这本质上意味着App.js 根本没有收到redux state/props。您是否尝试过手动将this.props.statethis.props.dispatch 传递给&lt;Navigation /&gt; 而不是连接它? @PredragBeocanin,我解决了错误,错误在configureStore,但现在我在导航中出现另一个错误:s 有趣的一天不是吗!如果您自己无法破解该问题,请发布另一个问题。另外,也许可以将解决方案发布为您自己问题的答案,以便其他发现此问题的人也知道您是如何解决它的! 【参考方案1】:

在 App.js 中,authState 未定义,因为您需要连接您的 mapStateToPropsmapDispatchToProps,否则 this.props 中将不可用。

应该是这样的:

App.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);

【讨论】:

【参考方案2】:

一个轻量级的 React-Native Redux 样板,具有随时可用的现代技术。这个 Repo 为您的下一个 React-Native 项目提供了一个良好的开端。 请检查链接

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

【讨论】:

以上是关于如何在 React Native 中使用 redux 在 props 中定义变量/方法的主要内容,如果未能解决你的问题,请参考以下文章

如何在 React Native 中使用 React Native Video 显示多个视频? [关闭]

React-native:如何在 React-native 中使用(和翻译)带有 jsx 的 typescript .tsx 文件?

如何在React Native中使用CreateBottomTabNavigator?

如何在 React Native 中的循环中查找

如何在 react-native 中使用 FormData?

如何使用 React-Native 在 iOS 中禁用屏幕截图