问题:无法在 redux 操作中重命名响应

我想在.then(...中重命名响应,因为它的调用与参数相同,但是得到

[1] ./src/actions/postsActions.js
[1]   Line 95:  'e' is not defined  no-undef

问题是显示消息的是dispatches action,并且它以addPost参数数据作为showMessage参数,并且其中没有消息属性。

例子:

export const addPost = data => dispatch => {
  dispatch({
    type: ADD_POST
  });
  fetch(API_URL + "/posts", {
    method: "POST",
    body: JSON.stringify(data),
    headers: {
      "Content-Type": "application/json",
      Authorization: JSON.parse(localStorage.getItem("token")),
      "Access-Control-Allow-Origin": "*"
    }
  })
    .then(res => res.json())
    .then(
      e =>
        dispatch({
          type: ADD_POST_SUCCESS,
          payload: e
        }),
      dispatch(showMessage(e)),
      setTimeout(() => {
        history.push("/");
        dispatch({ type: CLEAR_MESSAGE });
      }, 2000)
    )
    .catch(err =>
      dispatch({
        type: ADD_POST_FAILED,
        payload: err
      })
    );
};

解答

而是ecma6隐式return,添加块语句。

那里不需要return。用分号分隔语句。

then(e => {

      dispatch({type: ADD_POST_SUCCESS, payload: e});
      dispatch(showMessage(e));
      setTimeout(() => {
        history.push("/");
        dispatch({type: CLEAR_MESSAGE});
      }, 2000);

    });
Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐