0

注册护士: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. 请注意,调度函数可用于触发,但“状态”没有附加减速器“初始状态”。

请让我知道在新的 RN 导航中将减速器初始状态附加到各种屏幕的正确方法。

4

1 回答 1

0

我在你做错的地方得到了它,在你的 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
于 2017-04-06T08:41:08.533 回答