更新
Spread 语法允许您将数组传播到对象中(数组在技术上是对象,就像 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' }
因此,当您将数组传播到对象中时,您可能会得到某种有效的数据。但是,如果您提供的示例是您实际使用的示例,那么您将遇到问题。见下文。
=============
对于redux 中的reducer,当您对数组使用展开语法时,它会将数组中的每个项目展开到一个新数组中。和使用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 }
这是帮助您在 reducer 中保持数据不可变的两种方法。扩展语法复制数组项或对象键/值,而不是引用它们。如果您对嵌套对象或数组中的对象进行任何更改,则必须考虑到这一点,以确保获得新副本而不是变异数据。
如果您将数组作为对象键,那么您可以将整个对象分散到一个新对象中,然后根据需要覆盖单个键,包括需要使用扩展语法更新的数组键。例如,对示例代码的更新:
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 可能不应该根据一个动作来切换它发回的数据类型。那将是一个不可预知的混乱。
如果您想将每个键分解为一个单独的 reducer,您将拥有 3 个(图像、视频和 selectedVideo)并使用 combineReducers 创建您的状态对象。
import { combineReducers } from 'redux'
// import your separate reducer functions
export default combineReucers({
images,
videos,
selectedVideos
})
在这种情况下,每当您调度操作以生成完整的状态对象时,每个减速器都会运行。但是每个 reducer 只会处理其特定的 key,而不是整个 state 对象。因此,您只需要数组等键的数组更新逻辑。