问题
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