我正在使用react、Express和SQL创建的react全栈网站中进行基本问卷调查。
目前,我所要做的就是从react返回一条错误消息,并让我的前端显示它。
这是我的快捷终点。
app.post("/post-question-answers", async (req, res) => {
console.log("!called");
try {
await sql.connect(config);
// create Request object
let selectedWorkstation = req.body.selectedWorkstation;
var request = new sql.Request();
request.input(`SelectedWorkstation`, sql.NVarChar, selectedWorkstation);
let existingWSA = await request.execute("dbo.CheckIfWSAExists");
if (!existingWSA.recordset.length) {
console.info("hello from first if");
let user = req.body.user;
let results = req.body.results;
let completeToken = req.body.completeToken;
let date = req.body.date;
let questions = [];
let answers = [];
// let emails = [];
let questionIds = [];
let suggestedSolutions = [];
results.forEach(element => answers.push(element.answer));
results.forEach(element => questions.push(element.question));
// results.forEach(element => emails.push(element.email));
results.forEach(element => questionIds.push(element.questionId));
results.forEach(element =>
suggestedSolutions.push(element.suggestedSolution)
);
var request = new sql.Request();
request.input(`QuestionStatus`, sql.NVarChar, completeToken);
request.input(`Date`, sql.NVarChar, date);
request.input(`Email`, sql.NVarChar, user);
request.input(`SelectedWorkstation`, sql.NVarChar, selectedWorkstation);
let result = await request.execute("dbo.AddQuestionResponseHeader");
console.log("HERE");
console.log(result);
if (result.hasOwnProperty("recordset") && result.recordset.length) {
var recordsetRow = result.recordset[0];
if (recordsetRow.hasOwnProperty("createdId")) {
var id = recordsetRow.createdId;
console.log(id);
for (var i = 0; i < results.length; i++) {
var request = new sql.Request();
let answer = answers[i];
let question = questions[i];
// let email = emails[i];
let questionId = questionIds[i];
let solution = suggestedSolutions[i];
request.input(`WSAId`, sql.Int, id);
request.input(`Question`, sql.NVarChar, question);
request.input(`Answer`, sql.NVarChar, answer);
request.input(`Email`, sql.NVarChar, user);
request.input(`QuestionId`, sql.NVarChar, questionId);
// request.input(`CompleteToken`, sql.NVarChar, completeToken);
request.input(
`SelectedWorkstation`,
sql.NVarChar,
selectedWorkstation
);
request.input(`SuggestedSolution`, sql.NVarChar, solution);
request.execute("dbo.SubmitQuestionResponses", function(
err,
recordset
) {
if (err) console.log(err);
});
}
} else {
console.log("unexpected result format");
}
} else {
console.log("No results found");
}
} else {
// HERE is what I am asking about
console.info("This account exists");
let errorMessage =
"This Workstation currently has an assessment in progress";
res.status(409).json({
errorMessage: errorMessage
});
}
} catch (e) {
console.log(e);
}
});
所以这很好——回复在最后的else is(评论在哪里(。当工作站存在并且工作正常时,就会达到此值。然后,我尝试在其他内容中传递此错误消息。
这是我提交答案功能中的提取语句
submitAnswers() {
let selectedWorkstation = window.localStorage.getItem("Workstation");
let user = window.localStorage.getItem("User");
let completeToken = "";
let declinedCounter = 0;
if (questionCounter == this.state.questions.length) {
var today = new Date(),
date = `${today.getUTCFullYear()}-${today.getUTCMonth() +
1}-${today.getUTCDate()} ${today.getHours()}:${today.getMinutes()}:${today.getSeconds()}.${today.getMilliseconds()} `;
for (var i = 0; i < results.length; i++) {
if (results[i].answer == "P") {
declinedCounter++;
} else {
}
}
if (declinedCounter > 0) {
completeToken = "In Progress";
} else if (declinedCounter <= 0) {
completeToken = "Complete";
}
console.log(completeToken);
const data = {
completeToken,
results,
selectedWorkstation,
date,
user: user
};
fetch("/post-question-answers/", {
method: "POST", // or 'PUT'
headers: {
Accept: "application/json,",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}).then(({ errorMessage }) => {
this.setState({ errorMessage: errorMessage });
alert(this.setState.errorMessage);
// Here is what I am referencing
if (this.setState.errorMessage.length > 2) {
alert("test1");
} else if (this.setState.errorMessage.length < 2) {
alert("test2");
}
});
window.location.href = "http://localhost:3000/completed-assessment";
} else {
alert("Please enter all of The questions");
}
}
此错误消息在首次使用时已起作用一两次。然后它要么是未定义的,要么不会向用户发出任何警告。
我正在搜索不是每次存在工作站时都显示这一点的原因。因为它通常是未定义的或根本不会显示。
任何帮助都将不胜感激。
您访问状态变量不正确。使用this.state
而不是this.setState
访问状态变量。
此外,将警报放在setState的回调中。setState是异步的,所以当您在alert中使用this.state.errorMessage
时,它可能还没有更新。所以,不如试试这个:
this.setState({errorMessage}, () => {alert(this.state.errorMessage)})