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 对象。
添加回答
举报
