【问题标题】:State updating in reduxredux 中的状态更新
【发布时间】:2016-07-02 15:20:04
【问题描述】:

我是 redux 和 es6 语法的新手。问题来了:

有一个包含多个帖子的应用。

const initialState = {
  items: {
    3: {title: '1984'}, 
    6: {title: 'Mouse'}, 
    19:{title: 'War and peace'}
  }
}

应用收到一系列喜欢的帖子 ID:

dispatch(receiveLikedPosts(3, {id:3, ids: [3,6]}));

function receiveLikedPosts(ids) {
  return {
    type: LIKED_POSTS_RECEIVED,
    ids
  };
}

有一个帖子缩减器:

function posts(state = initialState, action) {
  switch (action.type) {
  case LIKED_POSTS_RECEIVED:
    // here I need to update my posts state: post.liked => true (only 3 and 6 post) 
  default:
    return state;
  }
}

1) 我必须更新我的减速器 LIKED_POSTS_RECEIVED 代码。不知道如何以正确的方式制作它。

2) 多次分派事件是否正确? (每个喜欢的帖子发送一次)

代码如下:

// action
let ids = [3,6]
for (let id of ids) {
  dispatch({type: LIKE, id});
}

// reducers
function post(state, action) {
  switch (action.type) {
  case LIKE:
    return Object.assign({}, state, {
      liked: true
    });
  default:
    return state;
  }
}

function posts(state = initialState, action) {
  switch (action.type) {
  case LIKE:
    return Object.assign({}, state, {
      [action.id]: post(state[action.id], action)
    });
  default:
    return state;
  }
}

【问题讨论】:

  • action 不应该引起其他的 action,但是 dispatch 很多 action 本身也不是坏事。
  • @dandavis "动作不应引起其他动作" - 除非您使用 thunk。

标签: javascript reactjs redux flux


【解决方案1】:

这让我很困惑:

dispatch(receiveLikedPosts(3, {id:3, ids: [3,6]}));

function receiveLikedPosts(ids) {
  return {
    type: LIKED_POSTS_RECEIVED,
    ids
  };
}

您的函数receiveLikedPosts 只接受一个参数,但您传递了两个参数。而且我不确定{ id: 3, ids: [3, 6] } 应该做什么。但是,这就是我要做的:

初始状态和reducer:

const initialState = {
  items: {
    3: { title: '1984', liked: false }, 
    6: { title: 'Mouse', liked: false }, 
    19: { title: 'War and peace', liked: false }
  }
};

function posts(state = initialState, action) {
  switch (action.type) {
    let newItems = {};

    case LIKED_POSTS_RECEIVED:
      // copy the current items into newItems
      newItems = {...state.items};

      // Loop through the liked IDs, set them to liked:true
      action.ids.forEach((likedId) => {
        newItems[likedId].liked = true;
      });

      // Return the new state
      return {
        ...state,
        items: newItems,
      }
    default:
      return state;
  }
}

动作创建者:

function receiveLikedPosts(ids) {
  return {
    type: LIKED_POSTS_RECEIVED,
    ids,
  };
}

最后,调度:

dispatch(receiveLikedPosts([3, 6]));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-19
    • 1970-01-01
    • 2018-06-29
    • 2018-02-11
    • 2019-07-28
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多