简体   繁体   English

Redux动作创建器语法

[英]Redux action creator syntax

function addTodoWithDispatch(text) {
  const action = {
    type: ADD_TODO,
    text
  }
  dispatch(action)
}

http://redux.js.org/docs/basics/Actions.html#action-creators http://redux.js.org/docs/basics/Actions.html#action-creators

I saw the code above from redux documentation. 我从redux文档中看到了上面的代码。 What I don't understand is the text in the action . 我不明白的是actiontext It doesn't look like a valid javascript object or array syntax. 它看起来不像是有效的javascript对象或数组语法。 Is it an ES6 new syntax? 它是ES6的新语法吗? Thanks. 谢谢。

It is just a new ES6 syntax , which simplifies creating properties on the literal syntax 它只是一种新的ES6语法 ,它简化了在文字语法上创建属性

In short, if the name is the same as the property, you only have to write it once 简而言之,如果名称与属性相同,则只需编写一次

So this would be exactly the same :) 所以这将完全一样:)

function addTodoWithDispatch(text) {
  const action = {
    type: ADD_TODO,
    text: text
  }
  dispatch(action)
}

In the above code 在上面的代码中

function addTodoWithDispatch(text) {
  const action = {
    type: ADD_TODO,
    text
  }
  dispatch(action)
}

here text is an example of object literal shorthand notation. 这里的text是对象文字简写表示法的一个例子。 ES6 gives you a shortcut for defining properties on an object whose value is equal to another variable with the same key. ES6为您提供了一个快捷方式,用于定义对象的属性,该对象的值等于具有相同键的另一个变量。

As has been said this is just shorthand for writing 如前所述,这只是写作的简写

const action = {
    type: ADD_TODO,
    text: text
  }
  dispatch(action)

Have a look at this blog 看看这个博客

If you look at the next page in document http://redux.js.org/docs/basics/Reducers.html 如果您查看文档http://redux.js.org/docs/basics/Reducers.html中的下一页

function todoApp(state = initialState, action) {
 switch (action.type) {
  case SET_VISIBILITY_FILTER:
  return Object.assign({}, state, {
    visibilityFilter: action.filter
  })
 case ADD_TODO:
  return Object.assign({}, state, {
    todos: [
      ...state.todos,
      {
        text: action.text,
        completed: false
      }
    ]
  })
case TOGGLE_TODO:
  return Object.assign({}, state, {
    todos: state.todos.map((todo, index) => {
      if(index === action.index) {
        return Object.assign({}, todo, {
          completed: !todo.completed
        })
      }
      return todo
    })
  })
default:
  return state
 }
}

It is expecting property name text. 它期待属性名称文本。 As @Icepickle mentioned it is a valid format but you can also change to below format: 正如@Icepickle所说,它是一种有效的格式,但您也可以更改为以下格式:

function addTodoWithDispatch(text) {
  const action = {
     type: ADD_TODO,
     text:text
   }
  dispatch(action)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM