注册护士:0.42
- 我尝试使用新的导航(已发布)+ redux,但我无法在商店通过的屏幕中将 redux 的初始状态映射到道具。
- 我跟着这个:https ://reactnavigation.org/docs/guides/redux
- 我已经编写了我的自定义减速器。
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
}
- 在 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>
);
}
}
- 在 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)
- 请注意,调度函数可用于触发,但“状态”没有附加减速器“初始状态”。
请让我知道在新的 RN 导航中将减速器初始状态附加到各种屏幕的正确方法。