【问题标题】:ReactJS : How to read value passed in Link react-router in another functional componentReactJS:如何在另一个功能组件中读取 Link react-router 中传递的值
【发布时间】:2021-10-24 18:12:51
【问题描述】:

我已按照Pass props in Link react-router上的建议进行操作

我将 Link 值发送到 ReactJS 功能组件,当访问它返回空时,我肯定在这里遗漏了一些基本的东西。

这是我的路线路径

            <Route path="/report/:id">
                <ReportPage />
            </Route>

试图从查询参数或状态参数中获取值的报告页面都返回空

const ReportPage = (props) => {
    const { query } = useParams();
    const { hello } = useState()

    console.log(query) // Return Empty for Try #2 
    console.log(hello) // Return Empty for Try #1
    console.log(this.props.match.params.hello) // Undefined for 

    return (
        <DashboardLayout>
            <h2> AMI Test Reports </h2>
        </DashboardLayout>
    )
}
                

正在链接的DashbaordPage

试过 1 使用状态

                   <Link
                    to={{
                        pathname: "/report/1",
                        state: {
                            hello: "Hello World"
                        }
                    }}>
                    Press Me
                </Link>

尝试 #2 使用查询

                   <Link
                    to={{
                        pathname: "/report/1",
                        query: "test"
                    }}>
                    Press Me
                </Link>

在另一个功能组件中访问链接中传递的值的正确方法是什么。

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

useParams 返回一个包含所有可用参数的对象。您目前拥有的是 useParams 返回一个包含不正确的 params 属性的对象。

你想要什么:

const { id } = useParams();

至于位置状态,您可以从 useLocation 而不是 useState 中获得。

const { state } = useLocation()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 2023-04-01
    • 2021-07-31
    • 2020-05-09
    • 2015-07-18
    相关资源
    最近更新 更多