reactjs - 子组件不渲染道具
问题描述
我遇到了一个问题ChildComponent没有使用 map 函数渲染数据,尽管 console.log(data) 每次我在MainComponent中单击获取 API 时都会打印数据。
单击时,MainComponent 应该为 Rick and Morty 的每个角色获取所有剧集的 API。handleClick 方法获取多个 API,可能是我调用错了吗?每次点击都会更新道具,我可以看到它,但没有呈现数据。
class MainComponent extends Component {
constructor(props) {
super(props);
this.state = { actors: [], episodes: [] };
this.handleClick = this.handleClick.bind(this);
}
handleClick(arr) {
const dataEpisodes = [];
arr.map((api) =>
axios.get(api).then((response) => dataEpisodes.push(response.data.name))
);
this.setState({ episodes: dataEpisodes });
}
componentDidMount() {
axios
.get("https://rickandmortyapi.com/api/character")
.then((response) => this.setState({ actors: response.data.results }));
}
render() {
console.log(this.state.episodes);
return (
<div className="container">
<div className="row g-3">
<div className="col-md-5 col-lg-4 order-md-last">
<ChildComponent episodes={this.state.episodes} />
</div>
<div className="col-md-7 col-lg-8 ">
<div className="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3">
{this.state.actors.map((actor) => (
<div key={actor.id} className="col m-3">
<div className="card shadow-sm">
<img
className="bd-placeholder-img card-img-top"
width="100%"
height="225"
src={actor.image}
role="img"
aria-label="Placeholder: Thumbnail"
preserveAspectRatio="xMidYMid slice"
focusable="false"
/>
<div className="card-body">
<h1 className="card-text">{actor.name}</h1>
<div className="d-flex justify-content-between align-items-center">
<div className="btn-group">
<button
onClick={() => this.handleClick(actor.episode)}
type="button"
className="btn btn-sm btn-outline-secondary"
>
Episodes
</button>
</div>
<small className="text-muted">{actor.species}</small>
</div>
</div>
</div>
</div>
))}
</div>
</div>
</div>
</div>
);
}
}
export default MainComponent;
这是我的 ChildComponent
const ChildComponent = (props) => {
const data = props.episodes;
console.log(data);
return (
<div>
<h1>Episodes</h1>
{data.map((i) => (
<h6>{i}</h6>
))}
</div>
);
};
export default ChildComponent;
解决方案
您的 API 调用是异步的,您需要等待它们完成才能设置状态。实现 fetch 调用的正确方法是利用Promise.all
which 等待所有的 Promise 解决。
handleClick(arr) {
const dataEpisodes = [];
const promises = arr.map((api) =>
axios.get(api).then((response) => response.data.name)
);
Promise.all(promises).then(dataEpisodes => this.setState({ episodes: dataEpisodes }));
}
推荐阅读
- powershell - 如何检查 Outlook 文件夹的创建日期和日期?
- reactjs - 在前端添加带有 React 的 .Net 应用程序并将 SQLite 添加到 Docker
- java - 与黄瓜一起使用宁静时无法读取应用程序 yaml
- docker - 如何增加 Docker 中的 FastAPI 超时以部署在 AWS EB 上?
- django-templates - Mailjet 模板语言(TWIG,PUG 语法) - 如何在内联样式道具中使用模板变量?
- c# - 按计划执行代码并跳过任务
- html - Bootstrap nav-item 定位在 justify-content-center 之外
- typescript - 在 monorepo 中跨多个包的 Material UI 模块增强
- javascript - 无法通过请求加载 GET 文件
- javascript - 重绘图表后,line_chart 的 Chart.js 问题未在 x 轴上显示所有日期