[英]React, redux state is dependent on other redux state
[英]How to destructure redux state in react redux?
我没有明白在...state
中使用...
的意义。 当我观看反应 redux 的教程时,他们提到它是 state 变量的解构,但你能解释一下我提到的观点吗?
export const productreducer=(state=initialstate,{type,payload})=>{
switch(type)
case ActionTypes.SETPRODUCTS:
return{...state,...payload}; //here I have a doubt
default:
return state
}
};
一般来说,假设你有
const a = { foo: 1, bar: 2 }
那么以下两个是等价的:
return { foo: a.foo, bar: b.bar }
和
return { ...a }
所以本质上, ...
将旧 object 中的所有元素复制到新的 object 中。
也就是说,现代 Redux 不会这样做。 现代 Redux 也不做 switch..case 减速器、ACTION_TYPES 或连接。 您可能一直在关注一个非常过时的教程。
我真的建议您遵循官方的Redux Essentials教程,该教程将从一开始就教您现代 Redux - 它对意外错误更安全,并且只有四分之一的代码。
这是传播语法。 在您的情况下,它从对象中获取所有键:值对并将它们组合成一个新的 object。 希望有片段会更清楚
const state = {a: 1, b: 2} const payload = {c: 3, d: 4} const result = {...state, ...payload} console.log(result)
So {...} refers to spread or expand out the iterable elements, Lets take an example, you cannot change the state directly in the redux store and therefore you need to make a copy and append the new payload to the state and return the state。
状态={ x:1, y:2 } 有效载荷={ y:5, z:6 }
{...state, ...有效载荷} // { x: 1, y: 5, z: 6 }
这会将旧的 state 更新为新的 state。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.