页面未呈现,引用TypeError: state is undefined
,并在 SelectForm.js :const filter = useSelector(state => state.filter);
中追溯到此行。
我花了数小时试图弄清楚我在做什么错。我尝试过createSelector,但是没有用。我已经尝试调度“获取初始状态”操作,但该操作不起作用。该组件包装在提供程序标签中。我不确定为什么我无法访问该州。在这一点上,我看不到我已经看了很长时间的任何缺陷。
代码段
reducer.js
let initialState = {
filter: {
country: null,
state: null,
level: null,
team: null
},
isDBConnecting: false,
isDBConnected: false,
isDBError: false
}
const SelectorReducer = (state=initialState, action) => {
switch (action.type) {
case 'DB_CONNECT_INIT':
return {
...state,
isDBConnecting: true,
isDBConnected: false,
isDBError: false,
};
...
...
}
export default SelectorReducer;
actions.js
export const initializeDBConnection = () => {
return {
type: 'DB_CONNECT_INIT'
}
};
ParentComponent.js
import React from 'react';
import { createStore } from 'redux';
import { Provider } from 'react-redux'; //import provider to provide component access to the state
//Component imports
import SelectForm from './components/SelectForm'
import SelectorReducer from '.../reducer.js'
const SelectorStore = createStore(SelectorReducer);
const ParentComponent = () => {
return (
<div className="page-container">
<div id="carousel">
<div id="wrapper">
<Provider store={SelectorStore}>
<SelectForm />
</Provider>
</div>
</div>
</div>
)
}
SelectForm.js(子组件,包装在上面的提供程序标签中)
//IMPORTS
import React from 'react'; //import react
import { useSelector, useDispatch } from 'react-redux';
//COMPONENT IMPORTS
import FormGroup from '../FormGroup';
import { * as actions } from '.../actions.js';
const SelectForm = (props) => {
//STATEFUL IMPORTS
//filter
const filter = useSelector(state => state.filter);
答案 0 :(得分:3)
在评论中回复@NicholasTower。我的reducer没有默认情况下
default: return state
将其放入即可解决问题。
答案 1 :(得分:0)
在ParentComponent.js内部,您说的是<Provider store={TeamSelectorStore}>
。我想你是说<Provider store={SelectorStore}>
答案 2 :(得分:0)
let filter = useSelector(state => {
console.log('State: ', state);
return state.pieChart.filter;
});
请确保您为state
使用了正确的对象。
添加用于调试的控制台并检查state
对象。很多时候,我们使用多个reducers
,这使我们的组件state
嵌套在全局对象中。