reactjs - Spring Boot 使用 React 添加 UI
问题描述
我有一个 Rest Api 项目,我用我的 2 个实体类执行了 CRUD 方法。我想用 React 添加这个项目的 UI。但我是新的 Reactjs,我不太了解。这是我的 Rest-Api 控制器和示例方法:
@CrossOrigin(origins = { "http://localhost:3000", "http://localhost:4200" })
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
StudentService studentService;
@GetMapping("/list")
public ResponseEntity<List<Student>> ListStudents() {
List<Student> theStudent = studentService.getStudents();
return new ResponseEntity<>(theStudent, HttpStatus.OK);
}
@GetMapping("/getStudent/{id}")
public ResponseEntity<Student> getStudentById(@PathVariable("id") int theId) {
Student theStudent = studentService.getStudentById(theId);
return new ResponseEntity<Student>(theStudent, HttpStatus.OK);
}
我设置了反应我的计算机并创建了一个新项目。但现在我不知道我用这个做什么。我如何连接 React 和我的 Rest-Api 项目。请帮帮我我该怎么办?
解决方案
正如我在评论中提到的,你必须向你的 api 发送一个 HTTP 请求。
你可以通过 axios 或 fetch 甚至 XMLHttpRequest 来完成。
然后你必须得到响应(如果它是一个 json,你可以使用 json2typescript 库将 json 转换为类模型),然后通过 setState 更改你的反应组件的状态并在页面中显示数据。
就个人而言,我的选择是 fetch api,这里是使用 fetch 的示例:
const response = fetch('server_URL:port/student', {method: "get"}).then(res => console.log(res));
这是使用 axios 的更完整的教程:https ://hackernoon.com/tutorial-how-to-make-http-requests-in-react-part-3-daa6b31b66be
- 更新 -
在这里您可以找到有关反应状态和组件的信息(您也可以找到示例)https://reactjs.org/docs/state-and-lifecycle.html
推荐阅读
- c# - 在写入期间锁定 Azure Blob
- facebook - 脸书ID错误
- spring-boot - 了解长生不老药
- c++ - C++ 中 extern "C" 与 extern "C" { } 的不同链接
- javascript - Firebase - 网络 - 在没有可用电子邮件的情况下验证帐户
- docker - .NET Core docker - Linux 容器。查找我的内置项目的特定文件
- java - 如何处理 Spring Data JDBC 中的软删除?
- java - java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/Row
- javascript - 使用 bandintown API 搜索地理区域中的所有事件
- python - 如何检查同一个字典中是否存在两个键值对