【问题标题】:How to use a class function to initialise redux state?如何使用类函数来初始化 redux 状态?
【发布时间】: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


    【解决方案1】:

    当 redux 调用你的 reducer 时,它会传入两个参数。第一个是redux状态,第二个是当前动作。无论您如何命名参数,情况都是如此。因此,由于您的函数如下所示:

    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
      }
    }
    

    ...那么redux状态将被分配给错误命名的变量“action”。同时,该动作不会分配给任何参数。初始的 redux 状态是未定义的,因此您会看到该异常。

    改为将您的函数更改为接受两个参数;状态和动作。换句话说,使用你的工作代码:

    function counter(state = 0, action) {
      switch (action.type) {
        case 'INCREMENT':
          return state + 1
        case 'DECREMENT':
          return state - 1
        default:
          return state
      }
    }
    

    这不在一个类中,但我不确定你为什么想要它。

    【讨论】:

      【解决方案2】:

      所以你需要传递两个参数。

      function todos(state = [], action) {
        switch (action.type) {
          case 'ADD_TODO':
            return state.concat([action.text])
          default:
            return state
        }
      }
      const store = createStore(todos, ['Use Redux'])
      

      看看https://redux.js.org/api/createstore

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-29
        • 2020-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多