【问题标题】:React routing throws error:Cannot read property 'push' of undefined for Browser router反应路由抛出错误:无法读取浏览器路由器未定义的属性“推送”
【发布时间】:2020-02-05 20:34:46
【问题描述】:

我有一个代码,我需要在单击按钮后显示主页。当我在其他页面中调用相同的路由“/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;

这是用户界面代码:

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;

【问题讨论】:

标签: reactjs react-router


【解决方案1】:

我不确定是不是拼写错误,但组件名称是 Displaypage 而路由组件是 Displaydata

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

**路线道具 所有三个渲染方法都将传递相同的三个路由道具

匹配 地点 历史**

【讨论】:

  • 是的,这是一个错字。它仅在包含 withRouter 后才有效
  • 我了解它的工作原理,但是在路由器下渲染的直接组件,默认情况下具有匹配、历史和位置道具。除非组件名称不是拼写错误。
【解决方案2】:

您是否使用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;

【讨论】:

    猜你喜欢
    • 2020-10-29
    • 1970-01-01
    • 2021-09-06
    • 2017-09-23
    • 2021-12-31
    • 2022-01-15
    • 2017-07-30
    • 2017-11-01
    • 1970-01-01
    相关资源
    最近更新 更多