【问题标题】:import browserHistory from react-router从 react-router 导入 browserHistory
【发布时间】:2019-06-17 00:56:00
【问题描述】:

我正在尝试导入 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>;
 }

}

【问题讨论】:

标签: reactjs react-native frontend


【解决方案1】:

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

对于react-router v4:

您应该在这里受益于 HOC withRouter。以下一种方式应用它,这将向您的组件传递一些额外的道具,这些道具将允许浏览浏览器历史记录

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>;
  )
}

【讨论】:

  • 我试图从一个页面重定向到另一个页面,当我用谷歌搜索它时,我发现了这个浏览器历史记录
  • 为什么你使用这个 HomWitRouter 它给了我这样的警告,像这样被定义但它的值从未使用过。
  • 您需要导出 HomeWithRouter 组件并使用它。或者在这个文件中使用它。
猜你喜欢
  • 2017-03-24
  • 2017-10-17
  • 2017-10-04
  • 2016-04-28
  • 1970-01-01
  • 2015-11-28
  • 1970-01-01
  • 2017-09-01
  • 2016-10-21
相关资源
最近更新 更多