根据JavaSpring请求在React中设置状态

根据JavaSpring请求在React中设置状态,java,json,reactjs,spring,Java,Json,Reactjs,Spring,我有一个带有React Front和Spring Java后端的小项目。目前,我正试图根据Spring方法的响应将数据设置为React“状态”。这是Java方法的外观: @CrossOrigin(origins = "http://localhost:3000") @GetMapping("/cities") public ResponseEntity getCity ()throws JsonProcessingException { L

我有一个带有React Front和Spring Java后端的小项目。目前,我正试图根据Spring方法的响应将数据设置为React“状态”。这是Java方法的外观:

    @CrossOrigin(origins = "http://localhost:3000")
@GetMapping("/cities")
public ResponseEntity getCity ()throws JsonProcessingException
{
    List <City> cities = cityRepository.findByName("New York");
    System.out.println(cities);
    return ResponseEntity.ok(objectMapper.writeValueAsString(cities));
}

但它不起作用。地区和人口仍然没有划分。有人能告诉我如何修复它吗?

我想这不是应用程序组件中的全部代码

实际上,我使用了更多的函数组件,但我认为您需要绑定处理程序:

constructor(props) {
   super(props);
   this.state = {
      population: '',
      district: ''
   };
   this.handleInputChang = this.handleInputChange.bind(this);
   this.handleCitySubmit = this.handleCitySubmit.bind(this);
}
或者只使用功能组件:)

您是否记录了您第一次解析的响应?我更喜欢使用catch进行错误处理

我认为你需要约束你的处理者:

constructor(props) {
   super(props);
   this.state = {
      population: '',
      district: ''
   };
   this.handleInputChang = this.handleInputChange.bind(this);
   this.handleCitySubmit = this.handleCitySubmit.bind(this);
}
对不起,它不起作用。我将在下面展示项目的所有React和Spring类:

首先,春天:

城市

城市报告

public interface CityRepository extends JpaRepository<City, Long> {

List<City> findByName(String name);
CityRepository公共接口扩展了JpaRepository{
列出findByName(字符串名称);
}

城市服务

    @RestController
public class CityService {

    @Autowired
    CityRepository cityRepository;

    @Autowired
    ObjectMapper objectMapper;

    @CrossOrigin(origins = "http://localhost:3000")
    @GetMapping("/cities")
    public ResponseEntity getCity ()throws JsonProcessingException
    {
        List <City> cities = cityRepository.findByName("New York");
        System.out.println(cities);
        return ResponseEntity.ok(objectMapper.writeValueAsString(cities));
    }
}
@RestController
公共级城市服务{
@自动连线
城市记忆体城市记忆体;
@自动连线
对象映射器对象映射器;
@交叉原点(原点=”http://localhost:3000")
@GetMapping(“/cities”)
公共响应getCity()抛出JsonProcessingException
{
List cities=cityRepository.findByName(“纽约”);
系统输出打印(城市);
返回ResponseEntity.ok(objectMapper.writeValueAsString(cities));
}
}
反应:

App.js

    class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
       population: '',
       district: ''
    };
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleCitySubmit = this.handleCitySubmit.bind(this);
 }

state = {
  district: '',
  population: '',
}

handleInputChange = (e) => {
  this.setState({
    value: e.target.value
  })
}

handleCitySubmit = e => {
  e.preventDefault()
  const API = `http://localhost:8080/cities`;

  fetch(API)
  .then(response => {
    if(response.ok){
  return response
}
throw Error("It doesn't works")
  })
  .then(response => response.json())
  .then(data => {
    this.setState({
      district: data.district,
      population: data.population

    })
  })
console.log('District info: '+this.state.district)
console.log('Population info: '+this.state.population)
}


  render (){
    return (
    <div className="App">
      <Form 
      value = {this.state.value}
      submit = {this.handleCitySubmit}
      />
      <Result/>
    </div>
  );
    }
}

export default App
App.js
类应用程序扩展组件{
建造师(道具){
超级(道具);
此.state={
人口:'',
地区:''
};
this.handleInputChange=this.handleInputChange.bind(this);
this.handleCitySubmit=this.handleCitySubmit.bind(this);
}
状态={
地区:'',
人口:'',
}
handleInputChange=(e)=>{
这是我的国家({
价值:即目标价值
})
}
handleCitySubmit=e=>{
e、 预防默认值()
常量API=`http://localhost:8080/cities`;
获取(API)
。然后(响应=>{
if(response.ok){
返回响应
}
抛出错误(“它不工作”)
})
.then(response=>response.json())
。然后(数据=>{
这是我的国家({
地区:data.district,
人口:数据。人口
})
})
console.log('District info:'+this.state.District)
console.log('填充信息:'+this.state.Population)
}
渲染(){
返回(
);
}
}
导出默认应用程序
Form.js

    const Form = props => {
return (
    <form onSubmit={props.submit}>
        <input 
        type ="text" 
        value = {props.value}
        placeholder="Enter city name"
        />
        <button>Find city </button>
    
    </form>
)
}

export default Form
const Form=props=>{
返回(
寻找城市
)
}
导出默认表单
Result.js

const Result = () => {
return (
    <div>City</div>
);
}

export default Result;
const Result=()=>{
返回(
城市
);
}
导出默认结果;

setState是一个异步操作,这意味着在状态正确设置之前完全可能进行这些console.log调用。这同样适用于渲染方法。我不确定您的具体错误是什么,但使用http请求的未定义问题通常是由于试图呈现依赖于状态的内容而导致的,而状态尚未设置。在您的情况下,可能是您的状态尚未设置。您可以尝试:

  render (){
    return (
    <div className="App">
      {this.state.value ? <Form 
      value = {this.state.value}
      submit = {this.handleCitySubmit}
      /> : <h1>State has not been set yet</h1>}
      <Result/>
    </div>
  );
    }
render(){
返回(
{this.state.value?:尚未设置状态}
);
}
它检查this.state.value是否实际具有null或undefined以外的值,并且仅当表单实际具有正确的值时才呈现该表单

PS:缩进(或者说缺少缩进)使函数难以阅读。我建议您使用IDE的格式化工具来正确缩进,这样代码就更容易为其他人阅读

  render (){
    return (
    <div className="App">
      {this.state.value ? <Form 
      value = {this.state.value}
      submit = {this.handleCitySubmit}
      /> : <h1>State has not been set yet</h1>}
      <Result/>
    </div>
  );
    }