RN:0.42
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
}

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>
);
}
}
&#13;
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)
&#13;
请告诉我将reducer initialState附加到新RN导航中各种屏幕的正确方法。
答案 0 :(得分: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