UPDATE
传播语法允许你传播的数组对象(数组是技术上对象,主要是在JS一切)。将数组分散到对象中时,它将为每个数组项添加一个key: value
对,其中键是索引,值是存储在数组中索引中的值。例如:
const arr = [1,2,3,4,5]
const obj = { ...arr } // { 0: 1, 1: 2, 2: 3, 3: 4, 4: 5 }
const arr2 = [{ name: 'x' }, { name: 'y' }]
const obj2 = { ...arr2 } // { 0: { name: 'x' }, 1: { name: 'y' } }
您还可以将字符串分散到数组和对象中。对于数组,它的行为类似于String.prototype.split
:
const txt = 'abcdefg'
const arr = [...txt] // ['a','b','c','d','e','f', 'g']
对于对象,它会通过字符分割字符串,并通过索引键分配:
const obj = { ...txt } // { 0:'a',1:'b',2:'c',3:'d',4:'e',5:'f',6:'g' }
所以,你可能会得到的数据排序作品当你将一个数组扩展到一个对象时。但是,如果您提供的示例是您实际使用的示例,那么您将遇到问题。见下文。
=============
在终极版减速的情况下,当您使用传播语法使用数组它传播从阵列中的每个项目进入一个新的数组。它基本上与使用concat
:
const arr = [1,2,3]
const arr2 = [4,5,6]
const arr3 = [...arr, ...arr2] // [1,2,3,4,5,6]
// same as arr.concat(arr2)
与对象,传播语法蔓延从一个对象key: value
对到另一个:
const obj = { a: 1, b: 2, c: 3 }
const newObj = { ...obj, x: 4, y: 5, z: 6 }
// { a: 1, b: 2, c: 3, x: 4, y: 5, z: 6 }
这两种方式来帮助保护您的数据不变的你减速。扩展语法复制数组项或对象键/值而不是引用它们。如果在数组中嵌套对象或对象进行任何更改,则必须考虑到这一点,以确保获得新副本而不是突变数据。
如果您有数组作为对象键,那么您可以将整个对象分散到一个新对象中,然后根据需要覆盖各个键,包括需要使用扩展语法更新的数组。例如,对示例代码的更新:
const initialState = {
images: [],
videos: [],
selectedVideo: ''
}
// you need all of your initialState here, not just one of the keys
export default function (state = initialState, action) {
switch (action.type) {
case types.SELECTED_VIDEO:
// spread all the existing data into your new state, replacing only the selectedVideo key
return {
...state,
selectedVideo: action.video
}
case types.SHUTTER_VIDEO_SUCCESS:
// spread current state into new state, replacing videos with the current state videos and the action videos
return {
...state,
videos: [...state.videos, ...action.videos]
}
default:
return state;
}
}
这显示更新状态对象以及作为数组的对象的特定键。
在你给的例子中,你正在改变你的状态结构。它以一个数组开始,然后有时返回一个数组(当SHUTTER_VIDEO_SUCCESS时)并且有时返回一个对象(当SELECTED_VIDEO时)。如果你想拥有一个reducer功能,你不会将你的initialState隔离到视频阵列。您需要手动管理所有状态树,如上所示。但是您的reducer可能不应该根据操作切换回送的数据类型。那将是一个不可预知的混乱。
如果您想将每个按键分解为单独的缩减器,您可以使用3个(图像,视频和selectedVideo)并使用combineReducers
来创建状态对象。
import { combineReducers } from 'redux'
// import your separate reducer functions
export default combineReucers({
images,
videos,
selectedVideos
})
在这种情况下,每当您调度一个动作来生成完整的状态对象时,每个reducer都会运行。但是每个reducer只会处理它的特定键,而不是整个状态对象。所以你只需要数组更新逻辑的键是
['...'不是操作符!](https://stackoverflow.com/questions/37151966/what-is-spreadelement- in-ecmascript-documentation-it-the-same-as-spread-oper/37152508#37152508) –