如何在新的 React Router v4 中访问历史对象

新手上路,请多包涵

我已经在其他线程中尝试了所有建议的方法,但它仍然无法正常工作,这就是我发布问题的原因。

所以我有 history.js 看起来像这样

import { createBrowserHistory } from 'history';

export default createBrowserHistory;

我的 index.js

 render((
        <Router history={history}>
            <div>
                <Route component={App}/>
            </div>
        </Router>
    ), document.getElementById('root')
);

Home.js 看起来像这样

class Home extends Component {
    handleSubmit(e) {
        e.preventDefault();

        let teacherName = e.target.elements[0].value;
        let teacherTopic = e.target.elements[1].value;
        let path = `/featured/${teacherName}/${teacherTopic}`;
        history.push(path);

    }

    render() {
        return (
            <div className="main-content home">
                <hr />
                <h3>Featured Teachers</h3>
                <form onSubmit={this.handleSubmit}>
                    <input type="text" placeholder="Name"/>
                    <input type="text" placeholder="Topic"/>
                    <button type="submit"> Submit </button>
                </form>
            </div>
        );
    }
}

export default Home;

Home.js 实际上在 app.js 中路由,而 app.js 在 index.js 中路由。

问题是我无法在任何地方访问历史对象。

我尝试过的方法如下

  1. this.context.history.push(path) 在 home.js 中 - 无法访问未定义的上下文

  2. this.props.history.push(path) 在 home.js 中 - 无法访问未定义的属性

  3. browserHistory.push(path) 在 index.js 中 - 现在已弃用

4)上面的方式 - _history2.default.push 不是函数

我在上面尝试过的方法均无效。第二个是最奇怪的,因为根据文档 https://reacttraining.com/react-router/web/api/Route/Route-render-methods ,我应该能够在任何地方访问历史对象作为道具

我知道以前访问历史记录的 v2 或 v3 方式也已弃用。

那么知道如何在 React Router v4 中访问 history 对象的人可以回答这个问题吗?谢谢。

原文由 forJ 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 281
2 个回答

在我看来,您可能缺少 withRouter 连接。这将使历史道具可用于该组件

...

import { withRouter } from 'react-router'

class Home extends Component {
  functionMethod() {
    const { history: { push } } = this.props;
    doStuff();
    push('/location');
  }
  ...
}

export default withRouter(Home);

https://reacttraining.com/react-router/web/api/withRouter

原文由 Thomas Ingalls 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用钩子: useHistory

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

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

原文由 Luhn 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题