商店没有reducer initialState

时间:2019-04-15 18:31:26

标签: react-native redux state store

我无法获得store 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;

在这里,我要初始化商店并将其传递给应用程序,这要感谢提供者:

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,但这给了我 {}

1 个答案:

答案 0 :(得分:1)

您在连接呼叫中缺少mapStateToProps参数。

export default connect()(App);

您需要指定映射功能,该功能将获取部分状态并将其传递给组件props。 要将整个状态映射到道具,请尝试以下操作:

export default connect(state=>state)(App)

更好的做法是仅传递组件需要的部分状态。这样,当状态的其他部分发生更改时,您将避免不必要的重新渲染。例如,如果您连接的组件仅需要用户名,则可以执行以下操作:

export default connect(state=>{firstName:state.currentUser.firstName})(App)