![](/img/trans.png)
[英]How can I fetch objects from an array from an array which match an array of id's?
[英]How can I display all the objects of array from fetch in div?
如何以正确的方式保存我的对象数组? 然后在 html 中显示它们? 控制台日志可以打印整个阵列,但在 html 中的工作方式不同
import React from "react";
import "./style.css";
class App extends React.Component {
constructor() {
super();
this.state = {
quotes: [],
};
}
componentDidMount() {
fetch("https://type.fit/api/quotes")
.then((response) => response.json())
.then((data) => this.setState({ quotes: data }));
}
render() {
console.log(this.state.quotes.text);
return (
<div>
<h1>{this.state.quotes[0].author}</h1>
</div>
);
}
}
export default App;
您可以通过 JSX 中的引号 map。
return (
<div>
{this.state.quotes && this.state.quotes.map(quote => (
<div>
<h1>{quote.author}</h1>
<p>{quote.content}</p>
</div>
))}
</div>
);
告诉我我是否误解了什么或是否有帮助:)
做这个:
const quotes = this.state.quotes.map((quote) => {
return (
<div>
<h1>{quote.author}</h1>
</div>
);
});
然后在你的主要组件的返回中使用这个引号,如下所示:
return(
<div>{quotes}</div>
)
你可以这样使用:
import React from "react";
import "./style.css";
class App extends React.Component {
constructor() {
super();
this.state = {
quotes : []
};
}
componentDidMount() {
fetch("https://type.fit/api/quotes")
.then((response) => response.json())
.then((data) => this.setState({ quotes: data }))
}
render() {
console.log(this.state.quotes.text)
return (
<div>
{this.state.quotes ?
{this.state.quotes.map(quotes.author=> (
<h1>{author}</h1>
))}
:
<h1>{"Not loaded"}</h1>
}
</div>
);
}
}
使用Array.prototype.map
生成 jsx 元素。 在渲染方法中:
render() {
retrun(
{this.state.quotes.map(quote => (
<div>
<h2>{qutoe.author}<h2>
</div>
))}
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.