reactjs - 简单的弹簧靴+反应组件
问题描述
我有一个带有 react 的 webapp,以及一个带有 spring boot 的后端 webapp。
我在 APP.js 上使用它
constructor(props) {
super(props);
this.state = {
greeting: "This is a false greeting"
}
}
componentDidMount() {
fetch("/test2").then(function(response) {
return response.text();
}).then((text) => {
this.setState({greeting: text})
});
}
这在控制器上:
@RestController
public class HelloController {
@RequestMapping("/test")
public String test() {
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
return "This is a greeting from spring";
}
它有效,与
{this.state.greeting}
我可以看到“这是春天的问候”我想从 app.js 发送一个值(一个用按钮选择的数字)到弹簧侧控制器,控制器会采用这个值,选择一个随机值,比较两个值,然后发送响应。
我被困在“将值从 app.js 发送到弹簧侧控制器”
有人能帮我吗 ?
解决方案
在您的 UI 上将查询参数附加到 GET 请求中的 URL。
constructor(props) {
super(props);
this.state = {
greeting: "This is a false greeting",
selectedNumber: 0 //update this state variable on button click
}
}
componentDidMount() {
fetch("/test2?selectedNumber=" + this.state.selectedNumber).then(function(response) {
return response.text();
}).then((response) => {
console.log(response);
});
}
在 Spring-boot API 控制器上,添加 RequestParam 以便 API 能够从请求中读取查询参数。
@RestController
public class HelloController {
@RequestMapping("/test2")
public String test2(@RequestParam("selectedNumber") int selectedNumber) {
System.out.println(selectedNumber);
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
return "This is a greeting from spring";
}
推荐阅读
- javascript - React 导入背景图片
- cardano - Daedalus 钱包如何识别有效的 cardano 支付地址?
- python - 用 numpy 在两个矩阵之间进行插值
- javascript - 在javascript中具有给定ID的组数组
- mysql - 如何使用对象数组从 JSON 列中查询数据
- python - 遇到内存限制时如何避免在python子进程模块中使用shell = True
- kubernetes - Kubernetes 入口 nginx 重定向到 https
- c++ - freeglut 库没有正确链接。有什么方法可以将链接器指向正确的位置?
- node.js - 如何创建可摇树的反应模块?package.json“出口”不工作
- ansible - 配置 ansible 任务以使 helm 部署对 Internet 连接问题具有容错能力的正确方法是什么?