构建前端应用:从 React 开发到部署
1. 前端交互逻辑与组件集成
在表单提交时,会调用服务器的 API 发送猜测结果。以下是处理响应的代码:
if (res.ok) {
res.json().then(json => {
if (json.correct) {
this.updateMessage("Congratulations! Your guess is correct");
} else {
this.updateMessage("Oops! Your guess " + json.resultAttempt + " is wrong, but keep playing!");
}
});
} else {
this.updateMessage("Error: server error or not available");
}
上述代码逻辑为:当收到响应后,先检查响应是否正常( res.ok
)。若正常,将响应解析为 JSON 格式,根据 json.correct
的值更新消息;若不正常,则更新消息为服务器错误或不可用。
完成组件代码编写后,需要将其集成到应用中。修改 App.js
文件,将组件添加为根组件的子组件:
import React from 'r