【发布时间】:2016-10-04 00:18:12
【问题描述】:
偶然发现这段代码学习redux和react。
我的问题是使用传播操作符时的最终结果如何。如果我理解正确,它基本上会将可迭代或数组转换为单独的参数。
所以我希望输出只是使用通过 ... 运算符获得的所有字段创建另一个 JSON 对象。
const INITIAL_STATE = { postsList: {posts: [], error:null, loading: false},
newPost:{post:null, error: null, loading: false},
activePost:{post:null, error:null, loading: false},
deletedPost: {post: null, error:null, loading: false},
};
export default function(state = INITIAL_STATE, action) {
let error;
switch(action.type) {
case FETCH_POSTS:// start fetching posts and set loading = true
return { ...state, postsList: {posts:[], error: null, loading: true} };
这是 FETCH_POSTS 的结果吗:
{
postsList: {posts: [], error:null, loading: false},
newPost:{post:null, error: null, loading: false},
activePost:{post:null, error:null, loading: false},
deletedPost: {post: null, error:null, loading: false, },
所以基本上它足够聪明,知道存在postsList 键并覆盖它?
现在依赖检查 react.js 应用程序的状态是否存在是反模式?意思是“如果这个键存在做这个”而不是“如果键值为空做这个”
你为什么不直接通过数组键来改变键的值呢? INITIAL_STATE['postsList'] = {...postsObject}
或者使用扩展运算符是新模式?
【问题讨论】:
-
FETCH_POSTS 的结果将是
{ postsList: {posts: [], error:null, loading: true}, newPost:{post:null, error: null, loading: false}, activePost:{post:null, error:null, loading: false}, deletedPost: {post: null, error:null, loading: false, },,因为这是在返回中设置的。...实质上替换了 Object.assign() developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
@rrostt 提到 Redux 状态 必须 被认为是不可变的。这里有一些关于如何做到这一点的好文档:redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html
标签: javascript reactjs redux