React路由抛出错误:无法读取浏览器路由器的未定义属性“ push”

时间:2019-10-08 14:23:31

标签: reactjs react-router

我有一个代码,单击该按钮后需要显示主页。当我在其他页面中调用相同的路由“ / Sub”时,它正在工作。     但是这里会抛出无法读取未定义的属性“ push”

Routes.js:

import React from 'react';
import { Switch, BrowserRouter, Route } from 'react-router-dom';

const Routes = () => (
    <BrowserRouter>
        <Switch>
            <Route exact path='/' component={Addpage} />
            <Route path='/New' component={Details} />
            <Route path='/Sub' component={Displaydata} />
        </Switch>
    </BrowserRouter>
) 
export default Routes;

这是UI代码:

class Displaypage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            Pageid: 1
        }
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleAddNew = this.handleAddNew.bind(this);
    }

    handleSubmit = s => {
        s.preventDefault();
        const Pageid = this.state.Pageid;
        this.props.history.push({
            pathname: "/Sub",
            state: {
                Pageid: this.state.Pageid;
            }
        });
    }

    render() {
        const submitbutton = <button onClick={this.handleSubmit}>Submit</button>
        return (
            <div >
                {submitbutton}
            </div>
        );
    }
}
export default Displaypage;

2 个答案:

答案 0 :(得分:0)

您使用https://reacttraining.com/react-router/web/api/withRouter定义了组件吗?

import { withRouter } from "react-router"

class Displaypage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            Pageid:1
}            
        this.handleSubmit=this.handleSubmit.bind(this);
        this.handleAddNew = this.handleAddNew.bind(this);
    }

handleSubmit = s => {
        s.preventDefault();
        const Pageid = this.state.Pageid;
        this.props.history.push({
            pathname: "/Sub",
            state: {
                Pageid: this.state.Pageid;
            }
        });
    }
     render() {

const submitbutton = <button onClick={this.handleSubmit}>Submit</button>

return (
            <div >                              
                {submitbutton}              

            </div>
        );

}
}   

const DisplaypageWithRouter = withRouter(Displaypage)

export default DisplaypageWithRouter;

答案 1 :(得分:0)

我不确定它是否有错字,但是组件名称是Displaypage而路由的组件是Displaydata吗?

除此之外,我没有发现任何错误,应该可以正常工作。正如其他答案所暗示的那样,withRouter下的直接组件不需要Router

**路线道具 所有这三种渲染方法都将通过相同的三个路由道具

匹配 位置 历史**