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

时间:2018-06-29 05:29:15

标签: javascript reactjs 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
      })
    );
};

2 个答案:

答案 0 :(得分:4)

代替function appendCustomHeader(element){ var url = element.href; // to get full url $.ajax({ type: 'GET', url: url, headers: { "CustomHeader": 'YourCustomHeader' }, success: function(res) { // here you make anything else with your response } }) return false; } 隐式ecma6,添加一个block语句。

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

return

答案 1 :(得分:1)

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