简体   繁体   English

我对 API 的调用没有更新 React 状态

[英]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.我是 React 的新手,但看着类似的问题和答案,我认为这应该有效。 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.我也没有收到任何错误,并且正在调用 fetch。

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在 setstate 回调中的控制台,您将在渲染函数中获得更新的状态或控制台

Your jsonData.name will not work because the request is return an array with multiple values with a key called name .您的jsonData.name将不起作用,因为该请求返回一个具有多个值的数组,其键名为name So jsonData.name will be undefined.所以jsonData.name将是未定义的。 Try jsonData[0].name .试试jsonData[0].name

If you want all the names use a map function like this:如果您希望所有名称都使用这样的 map 函数:

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

Also, you should do the console log like @Kishan said:另外,您应该像@Kishan 所说的那样执行控制台日志:

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 }); this.setState({names: jsonData.name });

should perhaps be也许应该是

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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