我是react和api的新手。我尝试从mongodb获取一个带有fetch的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;有谁知道怎么还身体吗?谢谢你的帮助。
发布于 2021-09-16 01:30:19
您需要首先在类组件中定义本地状态,然后使用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;发布于 2021-09-15 11:21:37
我不是这个主题的专家,但据我所知,从render可以看到你需要返回一个组件。此外,您可能首先希望将api响应数据保存到state,然后再使用它。从上面的代码可以看出,"data“在你的render方法中没有任何可见性。
https://stackoverflow.com/questions/69192074
复制相似问题