Redux action creator syntax

老子叫甜甜 提交于 2019-12-12 17:06:49

问题


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

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

I saw the code above from redux documentation. What I don't understand is the text in the action. It doesn't look like a valid javascript object or array syntax. Is it an ES6 new syntax? Thanks.


回答1:


It is just a new ES6 syntax, which simplifies creating properties on the literal syntax

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



回答2:


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. ES6 gives you a shortcut for defining properties on an object whose value is equal to another variable with the same key.

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




回答3:


If you look at the next page in document 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:

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


来源:https://stackoverflow.com/questions/41531565/redux-action-creator-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!