我正在学习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});
如果我更换
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]
相同的语义适用于对象:
o1 = { foo: 'bar' }
o2 = { bar: 'baz' }
o12 = { ...o1, ...o2 } // { foo: 'bar', bar: 'baz' }
您可以使用它来浅拷贝对象和数组:
a = [1, 2, 3]
aCopy = [...a] // [1, 2, 3], on a new array
o = { foo: 'bar' }
oCopy = { ...o } // { foo: 'bar' }, on a new object
查看Mozilla docs,这是所有javascript的绝佳来源。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句