我是 React 新手,但看着类似的问题和答案,我认为这应该有效。但它只是返回 null。如果我将默认状态设置为空数组,它仍然只会返回空数组。我也没有收到任何错误,并且正在调用 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);
});
在 setstate 回调中的控制台,您将在渲染函数中获得更新的状态或控制台
关于javascript - 我对 API 的调用并未更新 React 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59193956/