我正在使用react-router。我想检测我来自哪里的上一页(在同一个应用程序中)。我的上下文中有路由器。但是,我在路由器对象上看不到任何属性,例如“以前的路径”或历史记录。我该怎么做?
检测react-router中的先前路径?
IT技术
reactjs
react-router
2021-03-30 16:36:30
6个回答
您可以使用<Link>组件传递状态,在本例中为路径名:
<Link to={{pathname: '/nextpath', state: { prevPath: location.pathname }}}>Example Link</Link>
然后您可以prevPath从this.props.location.state下一个组件中访问
您可以在componentWillReceiveProps生命周期方法中保存以前的路径。该逻辑与文档的故障排除部分中提供的示例非常接近react-router。
<Route component={App}>
{/* ... other routes */}
</Route>
const App = React.createClass({
getInitialState() {
return { prevPath: '' }
},
componentWillReceiveProps(nextProps) {
if (nextProps.location !== this.props.location) {
this.setState({ prevPath: this.props.location })
}
}
})
最近,从状态访问它。
如果您正在使用,react-router-redux您可以创建一个减速器,该减速器与 react-router-redux 调度的事件挂钩。
export default function routerLocations(state = [], action) {
switch (action.type) {
case "@@router/LOCATION_CHANGE":
return [...state, action.payload]
default:
return state;
}
}
不要检查上一页是什么,而是从不同的角度解决问题。将当前页面作为props传递给您要导航到的组件或链接。
在我调用 history.push 或单击链接的上一个页面或组件中,我添加了我所在的当前页面的状态,例如
history.push(`/device/detail`, { from: 'device detail page' } );
然后我可以使用 history.location.state.from 访问上一页的内容
使用react-router 的useHistory钩子,在功能组件的无状态状态下跳转到之前的路径。有关更多信息,请点击链接https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/hooks.md#useroutematch
import { useHistory } from "react-router-dom";
function demo () {
let history = useHistory();
const goToPreviousPath = () => {
history.goBack()
}
return (
<div>
<Button
onClick={goToPreviousPath}
>
Back
</Button>
</div>
):
}