reactjs - 无法将索引传递给 react.js 中的子组件
问题描述
我的父组件中有这个“cardComponent”变量。它根据“drinkChoice”的用户输入将信息从数据库传递到我的子组件(InfoCard)。
let cardComponents = drinks.map((drink, index) =>{
if (drink.type === drinkChoice || drinkChoice === 'All') {
return (<InfoCard drinks={this.state.drinks} i ={ index } />)
}
if (drinkChoice === 'Favorites' && drink.favorite === true) {
return (<InfoCard drinks={this.state.drinks} i ={ index } />)
}
else {
return console.log("Nothing to report")
} })
在我的子组件中,我想呈现每种饮料的特定信息。
export default function InfoCard(props, i) {
const classes = useStyles();
return (
<Card className= {classes.root}>
title = { props.drinks[i].name }
</Card>
如果我控制台记录一个特定的索引(例如 console.log(props.drinks[1].name) ),它就可以工作。但是当我尝试使用索引时,我得到了错误
TypeError: props.drinks[i] 未定义
我很确定这是我忽略的某种愚蠢的语法问题,但它让我发疯了。
解决方案
React 函数式组件只接受一个参数,props
. 你已经定义了你的组件来获取一个它永远不会收到的额外组件。
它应该是:
export default function InfoCard(props) {
const classes = useStyles();
const { drinks, i } = props;
return (
<Card className= {classes.root}>
title = { drinks[i].name }
</Card>
);
}
或在函数签名中使用对象解构
export default function InfoCard({ drinks, i }) {
const classes = useStyles();
return (
<Card className= {classes.root}>
title = { drinks[i].name }
</Card>
);
}
改进的 API 可能只是将标题作为道具传递。
父母
<InfoCard title={this.state.drinks[index].name} />
孩子
export default function InfoCard({ title }) {
const classes = useStyles();
return (
<Card className= {classes.root}>
title = { title }
</Card>
);
}
推荐阅读
- c# - 查询 MongoDB C#:如何在 BsonDocument 中提取调用聚合方法产生的字段?
- apache-flink - Flink 1.10 on yarn 消耗 kafka 0.9 失败
- java - 如何在 GCP 上使用 G1GC 减少 Java 11 的 CPU 使用率
- header - 标题上的 SlickGrid 键盘导航
- laravel - Laravel QueryBuilder...GroupBy 和计数
- flutter - Flutter 中带有文本输入的标记
- opencl - clFlush(与 clFinish 相对)实际上有什么作用吗?
- php - WooCommerce 结帐页面 - 检查产品是否有特色
- gitlab-ci - Gitlab CI:手动运行单个任务
- attributes - 为什么 C++ 非静态数据成员需要唯一地址?