将值传递给道具 - 反应

时间:2021-07-20 06:17:55

标签: reactjs

我有一个名为 ArticlePage 的函数组件,以 match 作为道具

const ArticlePage = ({ match }) => {
    const name = match.params.name;
    const article = articleContent.find(article => article.name === name);

    if (!article) return <h1>Article does not exist!</h1>

    return (
        <>
        <h1>{article.title}</h1>
        {article.content.map((paragraph, key) => (
            <p key={key}>{paragraph}</p>
        ))}
        </>
    );
}

在 App.js 中,我调用了函数组件而不传递数据(鉴于这些事情我有两个问题。

<Route path = "/article/:name" component = {ArticlePage} />
  1. 在这行代码 const ArticlePage = ({ match }) => { 中解构的目的是什么,根据我的理解,以某种方式传递给 props 的值是 /article/:name,我不认为这个 url 参数是一个数组或一个对象。
  2. 传递给 ArticlePage 的 prop 的值是什么?如果是url参数:/article/:name,怎么样?为什么数据的传递看起来不像这样<Route path = "/article/:name" component = {ArticlePage(/article/:name)} /> 像一个普通的函数

1 个答案:

答案 0 :(得分:2)

React Router documentation 回答您的问题。 Route 组件会自动将 match 属性传递给您提供的任何组件。 match 道具包含有关用户当前网址如何与提供的路径匹配的详细信息。

由于您提供的路径包含 name 作为 URL 参数,因此 name 的值将作为 match 添加到 match.params.name 属性。