[英]Fetching data to a React.js component is not working
我有一个带有React组件的quote.jsx文件:
import React from 'react';
import fetch from 'node-fetch';
import './quotes.css';
export default class Quotes extends React.Component {
constructor(props) {
super(props);
}
render() {
return(
<div className="quotes">
{
fetch('/random_quote')
.then(res => res.json())
.then(json => json.text())
}
</div>
);
}
}
如您所见,它使用fetch来获取一个JSON对象,其中包含与引号(引号文本和作者)相关的数据,并显示一些此数据。
当我使用webpack捆绑系统时,收到以下警告消息:
./fe/~/encoding/lib/iconv-loader.js中的警告9:12-34关键依赖项:依赖项的请求是一个表达式
当我运行Web系统并访问应显示此组件的URL时,出现以下错误:
未捕获的错误:对象作为React子对象无效(找到:[object Promise])。 如果您打算渲染孩子的集合,请改用数组或使用React附加组件中的createFragment(object)包装对象。 检查
Quotes
的渲染方法。
我的后端没有错误,并且正在正确生成并返回JSON。 这不是问题。
我对React.js相对较新,以前从未见过此消息。
有人可以帮我弄这个吗? 我在整个星期天都在与这个错误进行斗争,没有更多选择可以解决它。
不要在render
内部执行fetch
,而要在componentDidMount
或componentWillMount
。
这是我将如何实施:
import React from 'react';
import fetch from 'node-fetch';
import './quotes.css';
export default class Quotes extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
fetch('/random_quote')
.then(res => res.json())
.then(json => {
this.setState({text: json.text()});
});
}
render() {
return(
<div className="quotes">
{this.state.text}
</div>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.