我一直在尝试将带有剩余服务后端的springboot应用程序连接到ReactJS前端。连接似乎有效,但是我无法通过我的React应用程序呈现结果。谢谢你。
下面是我的app.js文件
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
state = {
isLoading: true,
groups: []
};
async componentDidMount() {
const response = await fetch('api/blog');
const body = await response.json();
this.setState({ groups: body, isLoading: false });
}
render() {
const {groups, isLoading} = this.state;
if (isLoading) {
return <p>Loading...</p>;
}
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<div className="App-intro">
<h2>Example</h2>
{groups.map(group =>
<div key={group.id}>
{this.state.title}
</div>
)}
</div>
</header>
</div>
);
}
}
export default App;
和我的休息控制器如下 打包me.salisuwy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RequestMapping("/api")
@RestController
public class BlogController {
@Autowired
BlogRespository blogRespository;
@GetMapping("/blog")
public List<Blog> index(){
return blogRespository.findAll( );
}
@GetMapping("/blog/{id}")
public Blog show(@PathVariable String id){
int blogId = Integer.parseInt(id);
return blogRespository.findOne(blogId);
}
@PostMapping("/blog/search")
public List<Blog> search(@RequestBody Map<String, String> body){
String searchTerm = body.get("text");
return blogRespository.findByTitleContainingOrContentContaining(searchTerm, searchTerm);
}
@PostMapping("/blog")
public Blog create(@RequestBody Map<String, String> body){
String title = body.get("title");
String content = body.get("content");
return blogRespository.save(new Blog(title, content));
}
@PutMapping("/blog/{id}")
public Blog update(@PathVariable String id, @RequestBody Map<String, String> body){
int blogId = Integer.parseInt(id);
// getting blog
Blog blog = blogRespository.findOne(blogId);
blog.setTitle(body.get("title"));
blog.setContent(body.get("content"));
return blogRespository.save(blog);
}
@DeleteMapping("blog/{id}")
public boolean delete(@PathVariable String id){
int blogId = Integer.parseInt(id);
blogRespository.delete(blogId);
return true;
}
}
json输出如下
0:
id: 1
title: "Example1"
content: "Example Content1"
1:
id: 2
title: "Example1"
content: "Example Content1"
答案 0 :(得分:0)
您的render
方法中存在语义错误,因此,请执行以下操作:
{groups.map(group =>
<div key={group.id}>
{this.state.title}
</div>
)}
尝试一下:
{groups.map(group =>
<div key={group.id}>
{group.title}
</div>
)}