反应 api 获取
React api fetch
我是 React 和 api 的新手。我尝试从 mongodb 获取 api。
console.log 没问题,但我无法渲染它。
import React from 'react';
class Api extends React.Component {
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';
fetch(apiUrl)
.then((response) => response.json())
.then((data) => console.log('This is your data', data));
}
render() {
return {data};
}
}
export default Api;
有谁知道如何 return 正文?感谢您的帮助。
我不是该主题的专家,但据我所知,您需要 return 一个组件。
此外,您可能首先想将 api 响应数据保存到状态,然后再使用它。
从上面的代码中,“数据”在您的渲染方法中没有任何可见性。
您需要先在 class 组件中定义本地状态,然后使用 setState 设置值。当状态值改变时,组件将被重新渲染,render() 将刷新浏览器上的值。
试试这个:
import React from "react";
class Api extends React.Component {
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>my data: {this.state.data}</div>;
}
}
export default Api;
我是 React 和 api 的新手。我尝试从 mongodb 获取 api。 console.log 没问题,但我无法渲染它。
import React from 'react';
class Api extends React.Component {
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';
fetch(apiUrl)
.then((response) => response.json())
.then((data) => console.log('This is your data', data));
}
render() {
return {data};
}
}
export default Api;
有谁知道如何 return 正文?感谢您的帮助。
我不是该主题的专家,但据我所知,您需要 return 一个组件。 此外,您可能首先想将 api 响应数据保存到状态,然后再使用它。 从上面的代码中,“数据”在您的渲染方法中没有任何可见性。
您需要先在 class 组件中定义本地状态,然后使用 setState 设置值。当状态值改变时,组件将被重新渲染,render() 将刷新浏览器上的值。
试试这个:
import React from "react";
class Api extends React.Component {
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>my data: {this.state.data}</div>;
}
}
export default Api;