不带我到组件(react-router,link)

问题描述 投票:0回答:2

我遇到了react-router的问题。

我的应用程序显示食谱列表。在配方设计师中,您输入您的偏好(饮食,卡路里,过敏),将下一个信息发送到api,然后显示食谱列表。我想要显示菜肴的名称,照片和显示更多的按钮,这会将我移动到特定餐点的特定页面。

该组件负责呈现配方列表

class ListRecipes extends Component {
  render() {
    const { data } = this.props;

    const recipe = data
      ? data.hits.map((recipe, i) => {
          return <ItemRecipe recipe={recipe} key={i} />;
        })
      : null;

    return <ul>{recipe}</ul>;
  }
}

const mapStateToProps = state => {
  return {
    data: state.data
  };
};

ListRecipes = connect(
  mapStateToProps,
  null
)(ListRecipes);

export default ListRecipes;

该组件负责呈现单个配方

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


      <Link to={`/meals/${label}`} >
        <p>More information</p>
      </Link >
    </li>
  );
}

我的路由器看起来像这样

export default (
  <BrowserRouter>
    <Switch>
      <Route exact={true} path="/" component={Main} />
      <Route path="/form" component={FormPage} />
      <Route path="/meals" component={ListRecipes} />
      <Route path="/meals/:name" component={props => <DetailsRecipe {...props} />} />
      <Route path="*" component={NotFound} />
    </Switch>
  </BrowserRouter>
);

点击食谱后,网址的地址会发生变化,但不会将我转移到任何地方。 (http://localhost:3000/meals点击按钮http://localhost:3000/meals/Shrimp,%20Lemon,%20And%20Parsley%20Pasta

为什么点击之后

<Link to={`/meals/${label}`} >
    <p>More information</p>
</Link >

不带我去组件DetailsRecipe

reactjs react-redux react-router
2个回答
0
投票

您处于开关标记中,因此会呈现第一个匹配项。第一场比赛是为<Route path="/meals" component={ListRecipes} />所以它将被渲染。尝试将param精确添加到此路线route doc


1
投票

你需要使用带有ItemRecipe的withRouter HOC,因为它没有收到路由器道具

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


      <Link to={`/meals/${label}`} >
        <p>More information</p>
      </Link >
    </li>
  );
}

export default withRouter(ItemRecipe);

你也应该在使用enocdeURIComponent链接之前对你的URL参数进行编码,然后使用DetailsRecipedecodeURIComponent中对其进行解码

<Link to={`/meals/${encodeURIComponenent(label)}`} >
© www.soinside.com 2019 - 2024. All rights reserved.