Aip*_*ipi 5 javascript ecmascript-6 redux
我正在学习Redux,React和ES6.我已经用JS开发了,但是这个ES6的新世界让我很惊讶,有许多新的东西,比如"=>"来声明箭头函数和其他.然而,在这个新的Redux研究中,我...在我的代码中间面对.
贝娄我有一个例子:
import { combineReducers, createStore } from 'redux'
const userReducer = (state={}, action) => {
switch(action.type) {
case 'CHANGE_NAME':
state = {...state, name: action.payload};
break;
case 'CHANGE_AGE':
state = {...state, age: action.payload};
break;
}
return state;
};
const tweetsReducer = (state=[], action) => {
return state;
};
const reducers = combineReducers ({
user: userReducer,
tweetsReducer: tweetsReducer,
});
const store = createStore(reducers);
store.subscribe(() =>
console.log('The chage was: ', store.getState())
);
store.dispatch({type: 'CHANGE_NAME', payload: 'Will'})
store.dispatch({type: 'CHANGE_AGE', payload: 21});
Run Code Online (Sandbox Code Playgroud)
如果我替换
state = {...state, name: action.payload};
和
state = {...state, age: action.payload};
使用
它
state.name = action.payload;
并且
state.age = action.payload;
它起作用,但是年龄被一起插入对象名称,并且在第一种情况下插入名称并且插入年龄之后.
为什么会这样?我如何...在未来的代码中使用?它与国家有关吗?
那叫做传播算子.
它将值从对象或数组解包到另一个对象或数组中.例如,使用数组:
a1 = [1, 2, 3]
a2 = [4, 5, 6]
a12 = [...a1, ...a2] // [1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)
相同的语义适用于对象:
o1 = { foo: 'bar' }
o2 = { bar: 'baz' }
o12 = { ...o1, ...o2 } // { foo: 'bar', bar: 'baz' }
Run Code Online (Sandbox Code Playgroud)
您可以使用它来浅层复制对象和数组:
a = [1, 2, 3]
aCopy = [...a] // [1, 2, 3], on a new array
o = { foo: 'bar' }
oCopy = { ...o } // { foo: 'bar' }, on a new object
Run Code Online (Sandbox Code Playgroud)
查看Mozilla文档,这是javascript所有内容的绝佳来源.
| 归档时间: |
|
| 查看次数: |
4582 次 |
| 最近记录: |