首页 > 解决方案 > 通过 react-router Link 组件发送 props

问题描述

我在通过 react-router 的 Link 组件发送道具时遇到问题。这是我负责显示特定元素的组件:

const ItemRecipe = ({ recipe }) => {
  const { label, image } = recipe.recipe;
  return (
    <li>
      <p> {label} </p>
      <img src={image} alt="food" />


      <Link to={{pathname: `/meals/${label}`, params: recipe }}>

        <p>next</p>
      </Link >
    </li>
  );
}

单击后,我想打开带有特定食谱的页面。这个组件看起来像这样

class DetailsRecipe extends Component {
  constructor(props) {
    super(props);
    this.state = {
      recipe: props.match.params.recipe
    }
    console.log(this.state.recipe);
  }
  render () {
     <div>
         lorem lorem

      </div>
    )
  }
}

console.log(this.state.recipe)显示undefined. 如何解决此错误?如何通过 react-router 的 Link 组件正确发送数据?

我在stackoverflow上查看了类似的主题,但它无助于解决我的问题

标签: reactjsreact-router

解决方案


再看一下 Link 组件的文档。对象内部允许的to属性是:

  • 路径名:表示要链接到的路径的字符串。
  • search:查询参数的字符串表示。
  • 散列:要放入 URL 的散列,例如 #a-hash。
  • state:要持续到该位置的状态。

我猜你想使用state而不是params.

编辑:

所以你的代码看起来像这样:

<Link to={{pathname: `/meals/${label}`, state: {"recipe": recipe} }}>

然后您可以state像这样访问链接组件的内部:

this.state = {
  recipe: props.location.state.recipe
};

推荐阅读