即使在更新状态和执行 forEach 之后,反应组件也没有被填充
React Component Not Being Populated even after updating state and executing forEach
我想从 imgflip 模因 API 中获取模因,尽管我在我的控制台中看到了 HTTP 响应,但 DOM 没有被填充,我尝试了一切。
export default class MemesContainer extends Component {
constructor() {
super();
this.state = {
memes: [],
};
}
async componentDidMount() {
let req = await fetch("https://api.imgflip.com/get_memes");
let res = await req.json();
console.log(res.data.memes);
await this.setState({ memes: res.data.memes });
}
render() {
return (
<div className="container d-flex justify-content-center flex-wrap">
{this.state.memes.map((e) => {
<div className="card m-3" style={{ width: "18" + "rem" }}>
<img src={e.url} className="card-img-top" alt="..." />
<div className="card-body">
<h5 className="card-title">{e.name}</h5>
</div>
</div>;
})}
</div>
);
}
}
ForEach
没有 return 任何东西,它只是执行代码。此时你应该使用 Array.map
因为它意味着遍历数组并转换它的值和 return 它们。
export default class MemesContainer extends Component {
constructor() {
super();
this.state = {
memes: [],
};
}
async componentDidMount() {
let req = await fetch("https://api.imgflip.com/get_memes");
let res = await req.json();
console.log(res.data.memes);
await this.setState({ memes: res.data.memes });
}
render() {
return (
<div className="container d-flex justify-content-center flex-wrap">
{this.state.memes.map((e) => {
return (
<div className="card m-3" style={{ width: "18" + "rem" }}>
<img src={e.url} className="card-img-top" alt="..." />
<div className="card-body">
<h5 className="card-title">{e.name}</h5>
</div>
</div>
)
})}
</div>
);
}
}
我想从 imgflip 模因 API 中获取模因,尽管我在我的控制台中看到了 HTTP 响应,但 DOM 没有被填充,我尝试了一切。
export default class MemesContainer extends Component {
constructor() {
super();
this.state = {
memes: [],
};
}
async componentDidMount() {
let req = await fetch("https://api.imgflip.com/get_memes");
let res = await req.json();
console.log(res.data.memes);
await this.setState({ memes: res.data.memes });
}
render() {
return (
<div className="container d-flex justify-content-center flex-wrap">
{this.state.memes.map((e) => {
<div className="card m-3" style={{ width: "18" + "rem" }}>
<img src={e.url} className="card-img-top" alt="..." />
<div className="card-body">
<h5 className="card-title">{e.name}</h5>
</div>
</div>;
})}
</div>
);
}
}
ForEach
没有 return 任何东西,它只是执行代码。此时你应该使用 Array.map
因为它意味着遍历数组并转换它的值和 return 它们。
export default class MemesContainer extends Component {
constructor() {
super();
this.state = {
memes: [],
};
}
async componentDidMount() {
let req = await fetch("https://api.imgflip.com/get_memes");
let res = await req.json();
console.log(res.data.memes);
await this.setState({ memes: res.data.memes });
}
render() {
return (
<div className="container d-flex justify-content-center flex-wrap">
{this.state.memes.map((e) => {
return (
<div className="card m-3" style={{ width: "18" + "rem" }}>
<img src={e.url} className="card-img-top" alt="..." />
<div className="card-body">
<h5 className="card-title">{e.name}</h5>
</div>
</div>
)
})}
</div>
);
}
}