# react-native [0.42] - Новая навигация с Redux - Невозможно сопоставить состояние с реквизитами

RN: 0.42

  1. Я попытался использовать новую навигацию (которая была выпущена) + redux, и я не могу сопоставить начальное состояние redux с реквизитами на экране, где передается хранилище.
  2. Я следил за этим: https://reactnavigation.org/docs/guides/redux
  3. Я написал свой собственный редуктор.

export const types = {
  ...
}

export const actionCreators = {
  authenticate: () => async (dispatch, getState) => {
    ...
  }
}

const initialState = {
  auth: {
    ...
  }
}

export const reducer = (state = initialState, action) => {
  const {auth} = state
  const {type, payload, error} = action

  switch (type) {
    ...
  }

  return state
}

  1. В index.ios.js я объединил свой собственный редуктор

import { addNavigationHelpers } from 'react-navigation';
import * from 'appReducer';

const AppNavigator = StackNavigator({
  Home: { screen: MyTabNavigator },
});

const navReducer = (state, action) => {
  const newState = AppNavigator.router.getStateForAction(action, state);
  return (newState ? newState : state)
};

const appReducer = combineReducers({
  nav: navReducer,
  app: appReducer
});

@connect(state => ({
  nav: state.nav,
}))
class AppWithNavigationState extends React.Component {
  render() {
    return (
      <AppNavigator navigation={addNavigationHelpers({
        dispatch: this.props.dispatch,
        state: this.props.nav,
      })} />
    );
  }
}

const store = createStore(appReducer);

class App extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <AppWithNavigationState />
      </Provider>
    );
  }
}

  1. Внутри Home.js mapStateToProps не работает.

import React, { Component } from 'react'
import { View, Text, StyleSheet } from 'react-native'
import { connect } from 'react-redux'

import { actionCreators } from './appRedux'

const mapStateToProps = (state) => ({
  //This is the problem: Here 'state' has no 'auth' object attached to it
  auth: state.auth
})

class Home extends Component {

  componentWillMount() {
    const {dispatch} = this.props
    //Dispatch works
    dispatch(actionCreators.authenticate('testId', 'testToken'))
  }

  
  render() {
    const {auth} = this.props

    return (
      <View style={styles.container}>
          <Text>
            Welcome {auth['name']}
          </Text>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  }
})

export default connect(mapStateToProps)(Home)

  1. Обратите внимание, что функция диспетчеризации доступна для запуска, но к «состоянию» не прикреплен редуктор «initialState».

Пожалуйста, дайте мне знать, как правильно прикрепить reducer initialState к различным экранам в новой навигации RN.


person Jin    schedule 05.04.2017    source источник


Ответы (1)


Я понял, что вы делаете неправильно, в своем index.ios.js измените import * from 'appReducer'; на import {reducer} from 'appReducer';, тогда ваша текущая комбинированная функция редуктора будет похожа на

const appReducer = combineReducers({
  nav: navReducer,
  app: reducer
});

тогда в вашем home.js ваш mapStateToProps должен быть похож на

const mapStateToProps = (state) => ({
  //This is the problem: Here 'state' has no 'auth' object attached to it
  authState: state.app    //remember store only contains reducers as state that you had passed in combineReducer function
})

теперь используйте его в своем компоненте, например

this.props.authState.auth        //remember you had wrapped your auth object within initialState object
person Manjeet Singh    schedule 06.04.2017