如何解决道具对象与history.push为空
我有一个onClick
处理函数,用于过滤路由回相同组件但URL不同的数据。但是,当再次渲染相同的组件时,我无法访问props.location
。
为简洁起见,省略了很多代码。
组件:
import { useHistory } from 'react-router-dom';
const Dashboard = (props) => {
const history = useHistory();
console.log(props) // Empty
useEffect(() => {
console.log(props) // Empty
})
const handleFilter = argument => {
history.push('/filter'); // 'argument' left out to test routing,and to ensure props.location is accessible
}
return (
<button onClick={() => handleFilter('someArgumentHere')}>Filter</button>
)
}
路由器:
import React from 'react';
import {
browserRouter as Router,Switch,Route,Redirect,} from 'react-router-dom';
const PrivateRoute = ({ exact,path,component: Component }) => {
return (
<Route
exact={exact}
path={path}
render={props => (
<div>
<Navbar />
<Component {...props} />
</div>
)}
/>
);
};
<Router>
<Switch>
<PrivateRoute exact component={Dashboard} path="/" />
<PrivateRoute exact component={Dashboard} path="/filteredPriority" />
</Switch>
</Router>
当我单击handleFilter
时,路由有效。意思是,我的浏览器从'/'
导航到'/filteredPriority'
,并且看到了相同的内容。但是,由于这是一个过滤器,因此我想通过props.location
访问url参数,并且它为空。我不知道为什么。
解决方法
弄清楚了。需要将我的Dashboard
组件包装在withRouter中。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。