根据 react-router-dom 访问的最后一个页面更改"go back"按钮标签



我正在尝试使用react-router-dom实现一个返回按钮。该按钮工作正常,但我的问题是根据上次访问的页面更改其标签。 此按钮将仅出现在可以从两个不同页面访问的一个特定组件中。

import { useHistory } from "react-router-dom";
export const GoBack = ({ label }) => {
const history = useHistory();
return (
<div>
<button onClick={() => history.goBack()}>{label}</button>
</div>
)
};

干杯!

像这样传递您的当前位置:
使用Link

<Link to="/next" state={{ prevPath: this.props.location.pathname }}> Your Next path</Link>`

推送历史:

this.props.history.push({
pathname: '/next',
state: { prevPath: this.props.location.pathname }
})

不要忘记用withRouter包装你的组件(否则this.props.location将不可用(。
现在你可以在下一个组件中获取 prevPath

componentDidMount(){
const{prevPath}=this.props.location.state;   //I think it here but google to make sure
this.setState({
prevPath
})
}

现在你可以条件渲染你的按钮:

render(){
return(
<div>
{this.state.prevPath=="yourrequiredprevpath"&&<button>go johnny go</button>}
</div>
)
}

我强烈认为你的问题有一个更好、更稳定的答案,但由于没有人回答,这将让你继续前进,直到你找到它。

最新更新