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

Can't rename response in redux action

我想重命名 .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 there.Separate分号语句

then(e => {

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

    });

当您链接 then 中的多个函数时,请考虑下面的代码。引用中断

Promise.resolve(1)
.then(
  e => 
    console.log(e), 
    console.log(e) // this will give an error, as e is not accessible here
)

要么你必须像其他人建议的那样将所有内容包装在一个块中,要么如果执行顺序很重要,你可以这样做

Promise.resolve(1)
.then(e => {
  console.log('1. ' + e); // first function
  return e;
})
.then(e => {
  console.log('2. ' + e); // second function
  return e;
})