我无法创建将用户发送到上一页的按钮,我也不知道为什么,我已经在类组件上完成了工作并且可以工作,但是知道我正在尝试在功能组件并崩溃
查看代码:
import React, { Fragment } from "react";
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";
import Header from "../components/recursableComponents/Header";
import { BASE_URL } from "../consts";
function Collections(props) {
const { classes } = props;
const [collections, setCollection] = useState([]);
const [choosedCollection, setChoosedCollection] = useState("");
const getCollections = () => {
const user = new User();
const id_marca_estilo = user.user.id_marca_estilo;
return (
<Fragment>
<Header
title="Coleções"
rightIcon={null}
leftIcon={
<IconButton
aria-label="upload picture"
component="span"
className={classes.whiteButton}
onClick={() => props.history.goBack()}
>
<ArrowBack></ArrowBack>
</IconButton>
}
/>
答案 0 :(得分:1)
我假设您正在使用react-router-dom v5 +
您必须按如下所示使用useHistory
钩子
import { useHistory } from 'react-router-dom';
然后在您的功能组件中
const history = useHistory();
最后
onClick={() => history.goBack()}
答案 1 :(得分:0)
如果您使用的是react-router,则可以使用钩子访问历史记录:
import { useHistory } from "react-router-dom";
// (...)
function Collections(props) {
const history = useHistory(); // <=============
const { classes } = props;
const [collections, setCollection] = useState([]);
const [choosedCollection, setChoosedCollection] = useState("");
const getCollections = () => {
const user = new User();
const id_marca_estilo = user.user.id_marca_estilo;
return (
<Fragment>
<Header
title="Coleções"
rightIcon={null}
leftIcon={
<IconButton
aria-label="upload picture"
component="span"
className={classes.whiteButton}
onClick={() => history.goBack()}
>
<ArrowBack></ArrowBack>
</IconButton>
}
/>
查看文档以获取更多详细信息: https://reacttraining.com/react-router/web/api/Hooks/usehistory
答案 2 :(得分:0)
请检查此示例
import React from "react";
import {BrowserRouter as Router, Switch, Route, Link} from "react-router-dom";
import {withRouter} from "react-router";
export default function RoutingGoBackExample() {
return (
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/about/insideabout">Inside About</Link>
</li>
</ul>
<hr/>
<Switch>
<Route exact path="/">
<Home/>
</Route>
<Route exact path="/about">
<About/>
</Route>
<Route path="/about/insideabout">
<InsideAbout/>
</Route>
</Switch>
</div>
</Router>
);
}
function Home() {
return (
<div>
<h2>Home</h2>
</div>
);
}
const About = withRouter(({history, ...props}) => (
<div>
<h1>
About
<hr/>
<button onClick={() => {
// history.push('/')
history.goBack(-1);
}}>go back
</button>
</h1>
</div>
));
const InsideAbout = withRouter(({history, ...props}) => (
<h1 {...props}>
Inside About
<hr/>
<button onClick={() => {
history.goBack();
}}>go back
</button>
<button onClick={() => {
history.go(-2);
}}>go home
</button>
</h1>
));