首页 > 解决方案 > 根据 Java Spring 请求在 React 中设置状态

问题描述

我有一个带有 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));
}

当我在浏览器中点击

本地主机:8080/城市”

看起来像:

[{"name":"New York","countryCode":null,"population":8008278,"id":3793,"district":"New York"}]

国家代码无关紧要。它有@transient 注释。

在 React 我有一个状态和方法看起来像:

    class App extends Component {
    
    state = {
    population: '',
    district: ''
    }
    
    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('District info: '+this.state.population)
}

但它不起作用。地区和人口仍然不明确。有谁可以告诉我,如何解决?

标签: javajsonreactjsspring

解决方案


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>
  );
    }

它检查 this.state.value 是否实际上具有 null 或 undefined 以外的值,并且仅在 Form 实际具有正确值时才呈现 Form。

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


推荐阅读