0

公式ドキュメントから 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が初めてで、助けていただければ幸いです。ありがとう。

4

1 に答える 1

0

通常、関数を呼び出すtoString()と、関数の定義に使用されたリテラル ソース テキストが返されます。

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

myFunction.toString()

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

ただし、この場合、someActionCreator.toString()作成するアクション オブジェクトの一部となるアクション タイプを返す必要があります。

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

これを実現するために、これらのアクション CreatorscreateActionの実際の実装をオーバーライドしますtoString

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

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

  actionCreator.type = type

  return actionCreator;
}

ES6 オブジェクト リテラルの計算されたプロパティは、渡された値を自動的に文字列化しようとするため、これは特に便利です。そのため、アクション作成関数をオブジェクトのキーとして使用できるようになり、文字列型に変換されます。

const reducersObject = {
  [addTodo]: (state, action) => state.push(action.payload)
}
console.log(reducersObject);
// { "todos/addTodo": Function}
于 2020-04-15T15:46:14.890 に答える