代码之家  ›  专栏  ›  技术社区  ›  merko

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

  •  2
  • merko  · 技术社区  · 6 年前

    我想在中重命名响应 .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 回复  |  直到 6 年前
        1
  •  4
  •   RIYAJ KHAN    6 年前

    相反 ecma6 隐性的 return ,添加块语句。

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

    then(e => {
    
          dispatch({type: ADD_POST_SUCCESS, payload: e});
          dispatch(showMessage(e));
          setTimeout(() => {
            history.push("/");
            dispatch({type: CLEAR_MESSAGE});
          }, 2000);
    
        });
    
        2
  •  1
  •   Raghav Garg    6 年前

    当您将多个函数链接到 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;
    })