簡體   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