我正在Coursera的“使用React进行前端Web开发”课程中完成第4项作业。在这里,我想向服务器提交表单数据,然后向用户显示警报。并且代码运行正常,警报也显示出来,但随后发生了错误。
从堆栈溢出的相关文章中,我发现问题与以某种方式返回必须具有type属性的redux操作有关。 但我不知道如何以这种方式退还这笔款项。因为我不必执行任何操作。我只需要显示一个警报。
export const postFeedback = (firstname, lastname, email, telnum, agree, contactType, message) => {
const newFeedback = {
firstname:firstname,
lastname:lastname,
email:email,
telnum:telnum,
agree:agree,
contactType: contactType,
message:message,
}
newFeedback.date = new Date().toISOString();
return fetch(baseUrl + 'feedback', {
method: "POST",
body: JSON.stringify(newFeedback),
headers: {
"content-Type": "application/json"
},
credentials: "same-origin"
})
.then(res => {
if (res.ok){
return res
}else{
var error = new Error('Error '+ res.status + ': '+res.statusText);
error.response = res;
throw error;
}},
error => {
throw error;
})
.then(response => response.json())
.then(response => alert(response))
.catch(error => { console.log('post feedback', error.message);
alert('Your feedback could not be sent\nError: '+error.message);
});
}
一切正常。反馈将保存在数据库中,并且还会显示警报,然后显示错误“错误:操作必须是简单对象。将自定义中间件用于异步操作”。发生了。
答案 0 :(得分:1)
最后通过添加一个不执行任何操作的操作来解决该问题。这是代码的工作原理。如果可能有人
帮助我,我会发布它export const addFeedback = () => ({
type: ActionTypes.ADD_FEEDBCK,
})
export const postFeedback = (firstname, lastname, email, telnum, agree, contactType, message) =>
dispatch => {
const newFeedback = {
firstname:firstname,
lastname:lastname,
email:email,
telnum:telnum,
agree:agree,
contactType: contactType,
message:message,
}
newFeedback.date = new Date().toISOString();
return fetch(baseUrl + 'feedback', {
method: "POST",
body: JSON.stringify(newFeedback),
headers: {
"content-Type": "application/json"
},
credentials: "same-origin"
})
.then(res => {
if (res.ok){
return res
}else{
var error = new Error('Error '+ res.status + ': '+res.statusText);
error.response = res;
throw error;
}},
error => {
throw error;
})
.then(response => response.json())
.then(res => {
console.log(res);
alert(JSON.stringify(res));
return dispatch(addFeedback());
})
.catch(error => { console.log('post feedback', error.message);
alert('Your feedback could not be sent\nError: '+error.message);
});
}
答案 1 :(得分:0)
如果Redux是您的应用程序体系结构的一部分,则您可能希望使用Redux密集型中间件:https://www.npmjs.com/package/redux-thunk
以下是您的redux商店的常用设置:
import {createStore, applyMiddleware} from 'redux';
import rootReducer from '../reducers/rootReducer';
import thunk from 'redux-thunk';
export default function configureStore() {
return createStore(
rootReducer,
applyMiddleware(thunk)
);
}
...
以下是丹·阿布拉莫夫(Dan Abramov)提出的详细答案,说明了我们为什么要使用它:https://stackoverflow.com/a/34599594/5391520
答案 2 :(得分:0)
动作是纯函数,它应该返回对象。通常,它们可以很好地处理同步操作,但是对于异步操作,您应该返回带有dispatch参数的函数或可以使用中间件。
示例:-
const myAction = () => {
return (dispatch) => {
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve({type:'my_action', payload:{'sample': 'data'}})
}, 1000)
});
promise.then((rsp) => {
dispatch(rsp);
})
return promise;
}
}