简体   繁体   中英

React state is not being updated by my call to the API

I'm new to React but looking at similar questions and answers, I think this should be working. but it's just returning null. if I set the default state to an empty array it sill just returns and empty array. also i'm getting no errors and the fetch IS being called.

import React, { Component } from     "react";
import "./App.css";
import Header from "./Header";
import BreweriesContainer from "./BreweriesContainer";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      names: null
    };
  }

  componentDidMount() {
    fetch("https:api.openbrewerydb.org/breweries?by_state=Colorado")
      .then(response => response.json())
      .then(jsonData => {
        this.setState({ names: jsonData.name });
        console.log(this.state.names);
      });
  }

  render() {
    return (
      <div className="App">
    <Header />
    <p>{this.state.names}</p>
    <BreweriesContainer />
  </div>
    );
  }
}

export default App;
 this.setState({ names: jsonData.name },() =>{
        console.log(this.state.names);
});

console in setstate callback you will get updated state or console in render function

Your jsonData.name will not work because the request is return an array with multiple values with a key called name . So jsonData.name will be undefined. Try jsonData[0].name .

If you want all the names use a map function like this:

this.setState({ names: e.map( (object) => object.name ) });

Also, you should do the console log like @Kishan said:

this.setState({ names: jsonData.name },() =>{
        console.log(this.state.names);
});

在 setState 调用后立即 console.log 不会按预期工作,因为 setState 异步更新状态,并且 console.log 语句不会等待 setState 在打印出前一个/默认值之前完成

Is it not just a typo?

this.setState({ names: jsonData.name });

should perhaps be

this.setState({ names: jsonData.names });

Diogo 有你的答案, jsonData是一个数组,所以你需要使用jsonData[0]访问它

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM