我正在尝试使用 React 从 api 获取 json 数据并将其插入到 html 页面中。 函数如下:
function GetApiContent() {
let value = fetch(api2)
.then(response => response.json())
.then(results => {
console.log(results.title)
return {
title: results.title,
date: results.date,
hdurl: results.hdurl,
explanation: results.explanation,
}
})
.catch(err => {
console.log(err)
})
return (
<div>
<h3>{value.title}</h3>
</div>
)
}
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Api test</h1>
<Hola message="hello" />
</header>
<GetApiContent />
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
)
}
}
控制台日志可以工作并返回标题,但是当我在函数中返回它时,它显示 h3 标签 empty在网页中。
最佳答案
fetch
是一个异步的、基于 Promise 的操作,它不会立即返回值。它返回 Promise。这就是您的代码不起作用的原因。您基本上是在尝试显示 Promise 的 value
属性,但这不是您想要的。您想要等待 Promise 解析(换句话说:WAITING fetch 完成请求并解析响应)。您可以通过这种方式显示 api 中的值:
const getApiContent = () => fetch(api2).then(response => response.json())
class App extends Component {
state = {
title: ''
}
componentDidMount() {
getApiContent()
.then(result => this.setState({ title: result.title }))
.catch(err => console.log(err))
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Api test</h1>
<Hola message="hello" />
</header>
{!!this.state.title && (
<div>
<h3>{this.state.title}</h3>
</div>
)}
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
)
}
}
关于javascript - React fetch 返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47199245/