在redux中更新状态

时间:2016-03-16 16:00:02

标签: javascript reactjs redux flux

我是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)我必须更新我的Reducer LIKED_POSTS_RECEIVED代码。 Dunno如何以正确的方式制作它。

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;
  }
}

1 个答案:

答案 0 :(得分:2)

这让我感到困惑:

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

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

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

初始状态和缩减器:

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]));