繁体   English   中英

ReactJS:如何在另一个功能组件中读取链接 react-router 中传递的值

[英]ReactJS : How to read value passed in Link react-router in another functional component

我遵循了链接 react-router 中关于通行证道具的建议

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

这是我的路线路径

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

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

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使用 state

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

使用查询尝试#2

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

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

useParams 返回一个包含所有可用参数的 object。 您当前拥有的是 useParams 返回一个 object,其中包含一个不正确的params属性。

你想要什么:

const { id } = useParams();

至于位置 state,您将从 useLocation 而不是 useState 获得它。

const { state } = useLocation()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM