簡體   English   中英

React Router,在 router.js 中使用路由器屬性

[英]React Router, using router props in router.js

我正在嘗試使用“:group”將 state 傳遞到以下路由。 那可能嗎?

Router.js 文件(部分):

   const [ groups, setGroups ] = useState([])

    useEffect( () => {
        const result = () => {
            fetch("http://localhost:5000/groups", {method: "GET"})
                .then(response => response.json())
                .then(data => setGroups(data.groups))
                .catch(err => {
                    console.error(err)
                })
            }
            result()
    }, [])

    return (
       <Route 
           exact 
           path={`/groups/:group`} 
           render={ routeProps => 
              <GroupDetails 
                   routeProps={routeProps} 
          /> } 
       />
    )

GroupDetails 頁面:只需放置必要的代碼

const GroupDetails = ({routeProps, userId }) => {

    const [ details, setDetails ] = useState(routeProps.location.state)

現在,在我的群組頁面上,如果我點擊一個特定的群組,它會將我帶到該頁面。 但如果輸入“www.website.com/groups/groupname”,它將是未定義的,因為 routeProp.location.state 中沒有任何內容。

我正在考慮在頂部組件設置一個 groupId state 並在每次單擊組頁面時執行 setGroupId ,並將其作為/groups/${groupId}傳遞給路徑名。 我可以看到這個工作,但我想知道我是否可以使用 React Router 來做到這一點。

謝謝

好吧,您可以使用withRouter來獲取參數:group

這是 withRouter 的文檔: https://reacttraining.com/react-router/web/api/withRouter

此外,還有一個問題可能對您有所幫助: React - How to get parameter value from query string

一般location.state配合history.push使用。 當您渲染組件時,您也可以將孩子送入其中。

 const [ groups, setGroups ] = useState([]) useEffect( () => { const result = () => { fetch("http://localhost:5000/groups", {method: "GET"}).then(response => response.json()).then(data => setGroups(data.groups)).catch(err => { console.error(err) }) } result() }, []) return ( <Route exact path={`/groups/:group`} > <GroupDetails // pass whatever prop /> </Route> )

在 GroupDetails 組件中,您可以使用 react-router 提供的鈎子。他們可能會得到您想要的。

 const GroupDetails = ({routeProps, userId }) => { const history = useHistory() const {url, path} = useRouteMatch() const location = useLocation() const parameters = useParams() //:group will be found here const [ details, setDetails ] = useState(routeProps.location.state)

如果我沒有理解您的問題或者這沒有解決您的問題,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM