reactjs - 如何将数组值传递给另一个组件?
问题描述
我想将 brand.title 传递给子组件 - BrandDetail
这是我的尝试并且不起作用,它只是在父组件中呈现子组件,我希望它仅在子组件上呈现。
父组件:
class BrandsList extends React.Component {
state = {
brands: [],
};
fetchBrands = () => {
axios.get('http://127.0.0.1:8000/api/brands/').then((res) => {
this.setState({
brands: res.data,
});
});
};
componentDidMount() {
this.fetchBrands();
}
render() {
return (
<div style={{ margin: 22 }}>
{this.state.brands.map((brand) => (
<div key={brand.id}>
<Link to={`/brands/${brand.id}`}>{brand.title}</Link>
<BrandDetail brandName={brand.title} />
</div>
))}
</div>
);
}
}
export default BrandsList;
子组件:
import React, { useEffect, useState } from 'react';
import MyLayout from '../MyLayout/MyLayout';
class BrandDetail extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<MyLayout>
<div>Yes this is the detail page of {this.props.brandName}</div>
</MyLayout>
);
}
}
export default BrandDetail;
解决方案
更新: 这是我正在寻找的答案。
{ this.state.brands.map(brand =>
<div key={brand.id}>
<Link to={{
pathname: `/brands/${brand.title}`,
state: `${brand.title}`,
}}>{brand.title}
</Link>
</div>
)}
和子组件:
<div>Yes this is the detail page of {props.location.state}</div>
推荐阅读
- python - Dask延迟总和被杀死但有足够的资源
- arrays - 如何使用 React.js 中的 i18next 翻译与 .map 映射 .json 文件?
- python - 卡在机器上进行渗透测试学习,可能是 sudo 漏洞?
- algorithm - FIFO 何时胜过 LRU 替换算法?
- c++ - 关于 C++ 名称查找的困惑
- c# - Pascal 代码到 C# 代码的转换(ord 和 chr)
- node.js - Socket.io v3 不支持的协议版本错误
- php - 此集合实例上不存在属性 [id] - Laravel 6
- postgresql - API 结果与 SQL 查询不同的响应
- kotlin - 是否有更惯用的方式来执行订阅和异步/等待操作?