首页 > 解决方案 > 实现文章的正确方法及其在反应环境中的评论

问题描述

我正在实现文章视图以对其中的用户评论做出反应。我想知道我是否应该使用 redux 和操作,例如:FETCH_COMMENTS、EDIT_COMMENT 和 reducers 来更新状态(将信号注释添加到从 webabi 获取的初始状态并更改通过 ID 搜索的信号注释)或者只是简单地使用 fetch(post)在类组件(没有redux)中添加评论,然后再次获取以从api获取新的评论数组-在这种情况下,我将重新渲染所有评论而不是一个,但用户在添加自己的评论后会有新的评论,对吗?

这种情况的最佳解决方案是什么?提前致谢。

标签: reactjsreduxfetch

解决方案


我建议您将 axios(轻松检查获取错误)与通过 redux thunk 的异步请求结合使用,以确保您的数据将显示出来。

Redux thunk 很简单,就是将请求包含在动作中,并在其他动作中分派数据。典型的其他操作是“加载”和“错误”,但如果您愿意,可以跳过它们。这是我的一个项目的示例:

export const ActionGetGroupListLoading = bool => ({
  type: GET_GROUP_LIST_LOADING,
  isLoading: bool
});

export const ActionGetGroupListSuccess = groupList => ({
  type: GET_GROUP_LIST_SUCCESS,
  groupList
});

export const ActionGetGroupListError = bool => ({
  type: GET_GROUP_LIST_ERROR,
  hasErrored: bool
});


export const ActionGetGroupList = url => {

  return dispatch => {
    dispatch(ActionGetGroupListLoading(true));
    axios.get(url)
      .then(response => response.data)
      .then(grouplist => dispatch(ActionGetGroupListLoading(false)) && dispatch(ActionGetGroupListSuccess(grouplist)))
      .catch(() => dispatch(ActionGetGroupListError(true)));
  }
};

您可以在 ActionGetGroupList 中添加多个请求并在内部交叉数据,如下例所示:

export const ActionGetUserInfo = payload => ({
  type: GET_USER_INFO,
  payload
});

export const ActionLoadingUserInfo = bool => ({
  type: 'LOADING',
  isLoading: bool
});

export const ActionGetUserInfoAsync = (url, groupId, userId) => {

  return dispatch => {
    dispatch(ActionLoadingUserInfo(true));
    axios.post(url, {   
      groupId,
      userId,
    })
    .then(()=>fetch(`http://localhost/api/getuser/${userId}`))
    .then((response)=>response.json())
    .then(response => dispatch(ActionLoadingUserInfo(false)) && dispatch(ActionGetUserInfo(response)))
  }
};

推荐阅读