我想在.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
})
);
};
答案 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;
})