我是react和api的新手。我嘗試從mongodb獲取一個api。 console.log是好的,但我不能渲染它。
import React from react';
class Api extends React.composition {
componentDidMount() {
const apiUrl = 'https://us-east-1.aws.webhooks.mongodb-realm.com/api/client/v2.0/app/cv-xfzvw/service/cv/incoming_webhook/api?secret=cv'/span>;
fetch(apiUrl)
.then((response) => response.json()
.then((data) => console. log('this is your data', data))。
}
render() {
return {data};
}
}
export default Api;
有沒有人知道如何回傳正文?謝謝你的幫助。
uj5u.com熱心網友回復:
我不是這方面的專家,但就我從render中看到,你需要回傳一個組件。 此外,你可能首先想把你的api回應資料保存到state,然后再使用它。 從上面的代碼來看,"data "在你的render方法中沒有任何可見性。
uj5u.com熱心網友回復:
你需要先在你的類組件中定義本地狀態,然后使用setState來設定值。當狀態值改變時,組件將被重新渲染,render()將重繪 瀏覽器上的值。
試試這個:
import React from "react";
class Api extends React.composition {
constructor(props) {
super(props)。
this.state = {
data: null。
};
}
componentDidMount(){
const that = this;
const apiUrl =
"https://us-east-1.aws.webhooks.mongodb-realm.com/api/client/v2.0/app/cv-xfzvw/service/cv/incoming_webhook/api?secret=cv"。
fetch(apiUrl)
.then((res) => res.json()
.then((json) => {
that.setState({ data: JSON.stringify(json) })。)
});
}
render(){
return <div> 我的資料。{this.state.data}</div>。
}
}
export default Api;
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/307945.html
標籤:
上一篇:是否可以在條件下使用$size?
下一篇:讓用戶不關注硒的問題
