【发布时间】:2019-09-05 19:06:57
【问题描述】:
我无法获取 store reducer 的初始状态,因此我也无法映射到组件中的 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 状态连接到组件道具,但它给了我 {}。
【问题讨论】:
-
我认为您缺少 getState() 函数调用.. 尝试 JSON.stringify(Store.getState()) 。 createStore 返回一个具有 getState 和 dispatch 函数的 store 实例。使用 getState 检索当前状态
-
对不起,让我编辑我的问题。
-
现在您在 connect 调用中缺少 mapStateToProps 参数。您需要指定将获取部分状态并将其传递给组件道具的映射函数。将整个状态映射到道具试试这个:export default connect(state=>state)(App)
-
它工作,完美。写一个答案,我标记为正确答案!
标签: react-native redux state store