react native

React-Native undefined is not a

2018-09-18  本文已影响628人  niklause_sun
图片

前言

写RN总归是要佛系一点,比如之前并没有这个bug,版本更新又降级后就出了这个问题,最后没有办法查了很多资料才发现是react navigation的问题。

我的代码中

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

所以是缺少addListener这个方法的。

如何解决请继续往下看。有的朋友喜欢把他们导航状态和其他应用状态一样保存在同一个地方,利用Redux可以使你在其他地方很方便的去处理navigation的状态,并将新的状态保存下来。

  1. 为了在Redux中处理应用的导航状态,你需要把navigation的状态传到navigator中。

  2. 一旦你把自己的navigation的props传到navigator中,默认的navigation中的prop就会被销毁,所以你必须在navigation中传入state、dispatch和addListener属性。

而我们碰到的这个问题就是addListener没有传入到navigation中。

首先我们需要添加react-navigation-redux-helpers的库

 npm install --save react-navigation-redux-helpers

在Redex中,应用的state用reducer定义。每个navigation路由都有一个reducer,getStateForAction。下面是如何使用的代码

import {    createStackNavigator,  } from 'react-navigation'; 
import {    createStore,    applyMiddleware,    combineReducers,  } from 'redux';  
import {
    createReduxBoundAddListener,
    createReactNavigationReduxMiddleware,
    createNavigationReducer
} from 'react-navigation-redux-helpers';     
import { Provider, connect } from 'react-redux';
import React from 'react';
const AppNavigator = createStackNavigator(AppRouteConfigs);
const navReducer = createNavigationReducer(AppNavigator);
const appReducer = combineReducers({
  nav: navReducer,
  ...
}); 
// 一定要先使用createReactNavigationReduxMiddleware再使用
createReduxBoundAddListener()
const middleware = createReactNavigationReduxMiddleware(
    "root",
    state => state.nav,
); // 这个是必须的
const addListener = createReduxBoundAddListener("root"); // 这个也是必须的
class App extends React.Component {
    render() {
      return (
      {/*这个也是必须的*/}
      <AppNavigator navigation={{
          dispatch: this.props.dispatch,
          state: this.props.nav,
          addListener, 
       }} />
      );
    }
  }
const mapStateToProps = (state) => ({
    nav: state.nav
  });
const AppWithNavigationState = connect(mapStateToProps)(App);  ​ 
const store = createStore(
    appReducer,
    applyMiddleware(middleware),
  );
class Root extends React.Component {
    render() {
      return (
        <Provider store={store}>
          <AppWithNavigationState />
        </Provider>
      );
    }
  }

在你的代码中需要将这些必须的部分填上即可。

所以在我的代码中需要进行的修改就如下:

添加如下代码

const middleware = createReactNavigationReduxMiddleware(
  "root",
  state => state.nav,
);
const addListener = createReduxBoundAddListener("root");

然后在

render() {
    return (
      <AppNavigator
        navigation={
          addNavigationHelpers({
            dispatch: this.props.dispatch,
            state: this.props.nav,
            addListener // 加入这个即可
        })
      }
/>)}

即可解决这个问题
引用:https://reactnavigation.org/docs/en/redux-integration.html

上一篇 下一篇

猜你喜欢

热点阅读