2 回答

TA貢獻1797條經驗 獲得超4個贊
這不是基于類與功能組件的問題,而是路由如何工作的問題。包裹的孩子不會收到路由參數,但使用Route's component、render或childrenprop 渲染的任何東西都會收到。
路由渲染方法
<Switch>
<Route path="/first-page" component={FirstPage} />
<Route path="/second-page" component={SecondPage} />
</Switch>
編輯 pedantic-banzai-dhz27
另一種選擇是使用withRouterHOC 導出修飾的頁面組件,或者如果是功能組件,則使用鉤子。
帶路由器
您可以通過高階組件訪問history對象的屬性和最接近的屬性 <Route>。 每當渲染時,都會將 updated 、和props 傳遞給包裝的組件。matchwithRouterwithRoutermatchlocationhistory
const FirstPage = props => {
React.useEffect(() => {
console.log(props)
}, []);
return (
<div>
<h1>First Page</h1>
<p>Welcome to first page, {props.location.state.name}</p>
</div>
);
};
export default withRouter(FirstPage);
掛鉤
React Router 附帶了一些hooks允許您訪問路由器狀態并從組件內部執行導航的功能。
const FirstPage = props => {
const location = useLocation();
console.log(location);
return (
<div>
<h1>First Page</h1>
<p>Welcome to first page, {location.state.name}</p>
</div>
);
};
export default FirstPage;

TA貢獻1829條經驗 獲得超7個贊
我發現你的路由器有問題。而不是使用:
<Route path="/first-page">
<FirstPage/>
</Route>
利用:
<Route path="/first-page" component={FirstPage}/>
否則使用 library 提供的鉤子let location = useLocation();,這樣你就可以訪問 location 對象。
添加回答
舉報