我使用react + redux,当前收到以下错误消息:
index.js:2178 Warning: Failed prop type: The prop `store` is marked as required in `Root`, but its value is `undefined`.
in Root (at index.js:11)
index.js:2178 Warning: Failed prop type: The prop `store` is marked as required in `Provider`, but its value is `undefined`.
in Provider (at Root.js:8)
in Root (at index.js:11)
index.js:2178 Warning: Failed child context type: The child context `store` is marked as required in `Provider`, but its value is `undefined`.
in Provider (at Root.js:8)
in Root (at index.js:11)
我已经按照this post检查了我的进出口,但是无法弄清楚出了什么问题...
我的App.js如下所示:
import React, { Component } from 'react';
import {BrowserRouter as Router, Route} from 'react-router-dom';
import { Provider } from 'react-redux'
import { createStore } from 'redux';
import rootReducer from './redux/rootReducer'
import Home from './pages/Home.js';
const store = createStore(rootReducer);
console.log(store.getState());
class App extends Component {
render() {
return (
<Provider store={store}>
<Router>
<div>
<Route exact path="/" component={Home}/>
</div>
</Router>
</Provider >
);
}
}
export default App;
console.log显示存储不是未定义的,而是在进入提供程序之前处于初始状态。当前应该使用此状态的组件如下(某些逻辑仍然缺失):
import React, { Component } from 'react';
import { connect } from 'react-redux';
const mapStateToProps = (state) => {
return {
authStatus: state.authStatus
};
};
const mapDispatchToProps = (dispatch) => {
return {
updateAuthStatus: (authStatus) => {
dispatch({
type: 'UPDATE_AUTHSTATUS',
status: authStatus
})
}
};
};
class LoginPopover extends Component{
constructor() {
super();
}
render() {
console.log(authStatusChanged.authStatus);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(LoginPopover);
我的减速器功能:
import { UPDATE_AUTHSTATUS } from './actions'
const initialState = {
authStatus: ['unauthenticated'],
}
export const authStatusChanged = (state = initialState, action) => {
switch (action.type) {
case UPDATE_AUTHSTATUS:
return Object.assign({}, state, {
authStatus: action.status
});
default:
return state;
}
};
并组合减速器
import { combineReducers } from 'redux';
import { authStatusChanged } from './reducers';
const rootReducer = combineReducers({
authStatusChanged
});
export default rootReducer;
有任何想法吗?
最佳答案
减速器authStatusChanged
仅处理状态的一部分,即authStatusChanged
(或您传递给combineReducers
的任何名称),由于它返回一个对象(例如{authStatus: ['unauthenticated']}
),因此您的状态将如下所示:
state = {
authStatusChanged: {
authStatus: ['unauthenticated']
}
}
因此,当您尝试访问
mapStateToProps
中的状态时,请按以下方式进行操作:state.authStatusChanged.authStatus
而不是这样的state.authStatus
。