javascript – 如何在新的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中路由的,它在index.js中路由.

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

我尝试过的方法如下

1)home.js中的this.context.history.push(path) – 无法访问undefined的上下文

2)home.js中的this.props.history.push(path) – 无法访问undefined的道具

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

4)上面的方式 – _history2.default.push不是一个函数

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

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

那么知道如何在React Router v4中访问历史对象的人能回答这个问题吗?谢谢.

解决方法

在我看来,你可能会错过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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...