我正在尝试设置一个redux环境,但我不知道为什么会有这种行为。
我的reducer上有我的根状态:
export type RootState = {
counter: number;
};
const initialState: RootState = { counter: 0 };
const staticLesson = (state = initialState, action: any) => {
switch (action.type) {
case "INCREMENT":
return state.counter + 1;
default:
return state;
}
};
export default staticLesson;
然后在此处组合:
import staticLesson from "./staticLesson/index";
import { combineReducers } from "redux";
const rootReducer = combineReducers({
staticLesson,
});
export default rootReducer;
我用提供商包装我的应用程序:
import { createStore } from "redux";
import rootReducer from "./redux/reducers";
import { Provider } from "react-redux";
import { composeWithDevTools } from "redux-devtools-extension";
const store = createStore(rootReducer, composeWithDevTools());
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
然而,当我试图将其记录到我的组件中时,该值是未定义的
const Component = () => {
const staticLesson = useSelector((state: RootState) => state);
const dispatch = useDispatch();
console.log("counter", staticLesson.counter); <-- logs undefined
return (
...
)
}
我不明白的是,如果我只记录staticLesson
,为什么它会像预期的那样出现在我的控制台中。但是,如果我尝试访问对象上的值,而不是获取计数器的值0
。。。我得到undefined
。staticLesson
出现在我的devTools中,它就在那里。。。我被难住了,我搞砸了什么?
我确信您应该从useSelector
调用中的状态返回staticLesson
属性。在useSelector
中,您将返回整个状态。所以应该是:
const staticLesson = useSelector((state: RootState) => state.staticLesson);