React:如何通过来自 react-router-dom 的 Link 传递道具?

React: how to pass props through a Link from react-router-dom?

我正在尝试使用 <Link>title 从 props 传递到我的 Dishes 组件,但找不到解决方案。有什么建议吗?

import { Link } from "react-router-dom";

const Category = ({ title }) => {
  return (
    <Link to="/dishes">
      {title}
    </Link>
  );
};

export default Category;

App.js 看起来像这样:

return (
    <Router>
      <div className="App">
        <Route
          path="/"
          exact
          render={(props) => (
              <Categories recipes={recipes} />
          )}
        />
        <Route path="/dishes" component={Dishes} />
      </div>
    </Router>
  );

Link 可以传递一个状态对象,该对象可以通过位置从您的组件中检索到:

import { Link } from "react-router-dom";

const Category = ({ title }) => {
  return (
    <Link to={{ pathname: "/dishes", state: { title } }}>
      {title}
    </Link>
  );
};

export default Category;

然后你可以从 location 属性中提取 state。但是由于您仅在单击 Link 时才传递此值,因此如果您直接访问 Route,则 state 可以是 undefined。在这些情况下,您可能希望通过这种方式提供 defaultValue

const Dishes = ({location}) => {
  const { title = 'defaultValue' } = location.state || {}

  return <div>{title}</div>
}