Reactjs TypeError:无法读取属性';类型';开关中未定义的类型(action.type)
我第一次尝试关注youtube上关于redux的视频,但不明白为什么我得到了未定义的Reactjs TypeError:无法读取属性';类型';开关中未定义的类型(action.type),reactjs,redux,Reactjs,Redux,我第一次尝试关注youtube上关于redux的视频,但不明白为什么我得到了未定义的。我已经试着在谷歌上搜索答案了,但还是想不出来 import { createStore } from 'redux'; //action const up = () => { return { type: 'up' } } const down = () => { return { type: 'down' }
。我已经试着在谷歌上搜索答案了,但还是想不出来
import { createStore } from 'redux';
//action
const up = () => {
return {
type: 'up'
}
}
const down = () => {
return {
type: 'down'
}
}
//reducer
const counter = (state = 0, action) => {
switch(action.type){
case 'up':
return state + 1;
case 'down':
return state - 1;
}
}
let store = createStore(counter());
store.subscribe(() => console.log(store.getState()))
store.dispatch(up())
store.dispatch(down())
感谢您的帮助。您必须在
createStore
中传递实际函数,如下所示:
let store = createStore(counter);
这样,您传递的是
计数器的实际函数定义,而不仅仅是返回状态。您必须在createStore
中传递实际函数,如下所示:createStore(counter)
您的意思是此代码让store=createStore(counter())?我在那里制造错误?是的。将其替换为let store=createStore(counter)
btw,如何显示组件内部的状态值?如果您使用的是功能组件,则可能需要使用useSelector
hook()