我无法获得商店reducer的initialState,所以我也无法映射到组件中的props。
这是我的减速机:
const initialState = { currentUser: null }
export default function UserReducer(state = initialState, action){
let nextState;
switch(action.type){
case "USER_CONNECTED":
nextState = {
...state,
currentUser : action.value
}
return nextState;
case "USER_DECONNECTED":
nextState = {
...state,
currentUser : null
}
return nextState;
default:
return state;
}
}
这是配置商店的类:
import { createStore, combineReducers } from 'redux';
import UserReducer from './reducers/userReducer'
const rootReducer = combineReducers({
currentUser : UserReducer
});
const configureStore = () => {
return createStore(rootReducer);
}
export default configureStore;
这里是我初始化商店并通过提供商将其传递给App的地方:
import {AppRegistry} from 'react-native';
import React from 'react';
import App from './App';
import {name as appName} from './app.json';
import { Provider } from 'react-redux';
import configureStore from './store/store';
const Store = configureStore();
console.log("STORE :"+ JSON.stringify(Store.getState()));
const RNRedux = () => (
<Provider store = { Store }>
<App />
</Provider>
)
AppRegistry.registerComponent(appName, () => RNRedux);
当我打印上面的“STORE”时,它给了我正确的输出{currentUser:...}。然后我将App.js连接到商店,如下所示:
const AppNavigator = createStackNavigator(
{
NewAccount: NewAccountScreen,
Login: LoginScreen
},
{
initialRouteName: "Login"
}
);
const AppContainer = createAppContainer(AppNavigator);
export class App extends React.Component {
constructor(props, context){
super(props, context);
}
render() {
console.log("APP.JS : "+ JSON.stringify(this.props));
return (
<AppContainer />
)
}
}
export default connect()(App);
所以在最后一行我将整个App状态连接到组件props,但它给了我{}。
你在连接电话中缺少mapStateToProps
param。
export default connect()(App);
您需要指定将采用部分状态并将其传递给组件props的映射函数。要将整个州映射到道具,请尝试:
export default connect(state=>state)(App)
更好的做法是仅传递组件所需的部分状态。这样,当状态的某些其他部分发生变化时,您将避免不必要的重新渲染。例如,如果连接的组件只需要用户名,则可以执行以下操作:
export default connect(state=>{firstName:state.currentUser.firstName})(App)