此外,动作创建者重写 toString() 以便动作类型成为其字符串表示

Also, the action creator overrides toString() so that the action type becomes its string representation

我正在从官方文档学习 redux-toolkit 并遇到了这一行- Also, the action creator overrides toString() so that the action type becomes its string representation.这是什么意思?

这是文档中的代码:

const INCREMENT = 'counter/increment'

function increment(amount) {
  return {
    type: INCREMENT,
    payload: amount
  }
}

const action = increment(3)
// { type: 'counter/increment', payload: 3 }
const increment = createAction('counter/increment')

let action = increment()
// { type: 'counter/increment' }

action = increment(3)
// returns { type: 'counter/increment', payload: 3 }

console.log(increment.toString())
// 'counter/increment'

console.log(`The action type is: ${increment}`)
// 'The action type is: counter/increment'

所以,例如,当我写类似

的东西时
const increment = createAction("INCREMENT")
console.log(increment.toString())

正在记录 INCREMENT。那么这是 覆盖 toString() 吗?我真的很困惑。

我是 redux-toolkit 的新手,如有任何帮助,我们将不胜感激。谢谢。

通常,如果您在函数上调用 toString(),它 return 是用于定义函数的文字源文本:

function myFunction() {
  const a = 42;
  console.log(a);
}

myFunction.toString()

"function myFunction() {
  const a = 42;
  console.log(a);
}"

但是,在这种情况下,我们希望 someActionCreator.toString() 到 return 将成为其创建的操作对象的一部分的操作类型:

const addTodo = createAction("todos/addTodo");
console.log(addTodo("Buy milk"));
// {type: "todos/addTodo", payload: "Buy milk"}
console.log(addTodo.toString());
// "todos/addTodo"

要做到这一点,createAction overrides the actual implementation of toString for these action creators

export function createAction(type: string): any {
  function actionCreator(...args: any[]) {
    return { type, payload: args[0] }
  }

  actionCreator.toString = () => `${type}`

  actionCreator.type = type

  return actionCreator;
}

这特别有用,因为 ES6 对象字面量计算属性会自动尝试对您传入的任何值进行字符串化。因此,您现在可以使用 action creator 函数作为对象中的键,它会被转换到类型字符串:

const reducersObject = {
  [addTodo]: (state, action) => state.push(action.payload)
}
console.log(reducersObject);
// { "todos/addTodo": Function}