【发布时间】:2019-03-11 19:27:46
【问题描述】:
我正在尝试从类中定义的函数创建一个 redux 状态。我在使用时收到Uncaught TypeError: Cannot read property 'type' of undefined:
var c = new Counter(0)
counter = c.state
let store = createStore(counter)
但是如果我使用functioncounter(state = 0, action),那么它可以正常工作。
import { createStore } from 'redux'
class Counter {
constructor(s) {
this.s = s
}
state(action) {
console.log("action" + action)
switch (action.type) {
case 'INCREMENT':
return this.s + 1;
case 'DECREMENT':
return this.s - 1;
default:
return this.s
}
}
}
function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
var c = new Counter(0)
counter = c.state
let store = createStore(counter) // not working
store.subscribe(() => console.log(store.getState()))
store.dispatch({ type: 'INCREMENT' })
store.dispatch({ type: 'INCREMENT' })
store.dispatch({ type: 'DECREMENT' })
export default store
如何使用类并给出初始化状态的函数?
【问题讨论】:
标签: javascript reactjs redux state