gpt4 book ai didi

reactjs - 从 react-router 导入 browserHistory

转载 作者:行者123 更新时间:2023-12-01 21:59:14 26 4
gpt4 key购买 nike

我正在尝试导入 browserHistory,但出现类似这样的错误。

 ./src/App.js
Attempted import error: 'browserHistory' is not exported from 'react-
router'.

我的代码是:

import React, { Component } from "react";
import { browserHistory } from "react-router";

import App from "./App";
class Home extends Component {
home = () => {
browserHistory.push("/home");
};
state = {};
render() {
return <button onClick={this.home} className="btn btn-outline-light">
Logout
</button>;
}

最佳答案

据我了解,您的主要目的是以正确的方式更改浏览器 URL,而不是实际导入 browserHistory

对于 react-router v4:

你应该从 HOC withRouter 中受益。以下一种方式应用它,这会将一些额外的 Prop 传递到您的组件中,这些 Prop 将允许浏览浏览器历史记录

import { withRouter } from "react-router-dom";

class Home extends Component {
home = () => {
// - you can now access this.props.history for navigation
this.props.history.push("/home");
};

render() {
return (
<button onClick={this.home} className="btn btn-outline-light">
Logout
</button>;
)
}

const HomeWitRouter = withRouter(Home);

对于 react-router v5 和 React Hooks,这可能看起来像:

import { useHistory } from "react-router-dom";

export const Home = () => {
const history = useHistory();
const goHome = () => {
history.push("/home");
};

return (
<button onClick={goHome} className="btn btn-outline-light">
Logout
</button>;
)
}

关于reactjs - 从 react-router 导入 browserHistory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54327167/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com