首页 > 解决方案 > 无法将索引传递给 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] 未定义

我很确定这是我忽略的某种愚蠢的语法问题,但它让我发疯了。

标签: reactjscomponents

解决方案


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>
  );
}

推荐阅读