react-router类型错误:_this.props.history 未定义

IT技术 reactjs react-router
2021-04-21 18:48:23

我正在使用 react-router 和 react js,我遵循他们的文档但面临这个错误

编译时显示错误,

TypeError: _this.props.history is undefined

这是我的 index.js 文件

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';

ReactDOM.render(
  <Router history={browserHistory}>
    <Route path="/" component={App}>

    </Route>
  </Router>
  ,
  document.getElementById('root')
);

这是我的 App.js 文件

import React, { Component } from 'react';
import './App.css';

class App extends Component {
    constructor(props){
        super(props);

        this.state = {
            headerText: "Props from Header.",
            contentText: "Props from content."
        };
    }
    render() {
        return (
          <div className="App">
            <ul>
                <li><a href="">Home</a></li>
                <li><a href="">Home</a></li>
                <li><a href="">Home</a></li>
            </ul>
          </div>
        );
    }
}

export default App;
6个回答

这是因为 React Router 从 4.0.0 开始发生了变化。您现在应该在使用BrowserRouterfrom react-router-dompackage 时使用browserHistory. 所以你的代码看起来像:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
import { BrowserRouter, Route } from 'react-router-dom';

ReactDOM.render(
    <BrowserRouter>
        <Route path="/" component={ App }/>
    </BrowserRouter>, document.getElementById('root')
);

当然,您需要先安装react-router-dom

还要注意的是,如果你使用一个以上的Route元素,你将不得不使用一个Switch为解释在这个答案

对我来说,解决方案是改变

1) 组件作为子组件

<Route path="/path">
 <MyComponent/>
</Route>

2)组件作为“组件”props

<Route path="/path" component={MyComponent}>
</Route>

它以两种方式呈现,所以对我来说很困惑,在示例中,他们提供了第一个示例中的代码。(我目前使用的是“react-router-dom”包的 5.1.2 版)。

更新

您也可以使用这种方式(对于子组件(“MyComponent”的子组件)仅适用于这种方式)

import {withRouter} from 'react-router-dom';

const componentClassWithHistory = withRouter(ChildComponent);
export {componentClassWithHistory as ChildComponent};

或默认导出

export default withRouter(ChildComponent)

或typescript

const componentClassWithHistory = (withRouter(ChildComponent as any) as any);
export {componentClassWithHistory as ChildComponent};

来源:https : //reacttraining.com/react-router/core/api/withRouter

希望它可以帮助某人。

在这里也一样,但我想保留我的组件作为孩子。您可以通过向每个组件添加 2 行来启用 withRouter: 1) import { withRouter } from 'react-router-dom'; 2) 导出默认 withRouter(Home); 这解决了我所有的问题。这个家伙博客的完整细节:dev.to/kozakrisz/...
2021-06-06 18:48:23
对于功能组件最好使用useHistory hook;
2021-06-18 18:48:23

你在使用 npm 吗?我的 package.json 中的 "react-router": "^4.0.0" 也有同样的问题。将其更改为“react-router”:“^3.0.2”解决了我的问题。

"react-router": "^3.0.2" 对我有用。但不明白为什么 4.0.0 不起作用。
2021-06-10 18:48:23
我也是)我只是将它与我​​上次工作的 package.json 进行了比较。
2021-06-10 18:48:23
当您遵循官方教程并且第 1 课不起作用时,这不是一个好兆头:>
2021-06-21 18:48:23

我的 Form 组件有问题。

this.props.history.push('/') 未定义。

为了解决这个问题,我添加了import {withRouter} from 'react-router-dom' 然后将默认组件导出为: export default withRouter(connect(mapStateToProps)(CustomForm));

import React from "react";
import { Form, Input, Button } from "antd";
import { connect } from "react-redux";
import {withRouter} from 'react-router-dom'
import axios from "axios";

const FormItem = Form.Item;


class CustomForm extends React.Component {

  handleFormSubmit = async (event, requestType, articleID, ) => {
    event.preventDefault();

const postObj = {
  title: event.target.elements.title.value,
  content: event.target.elements.content.value
}

axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
axios.defaults.xsrfCookieName = "csrftoken";
axios.defaults.headers = {
  "Content-Type": "application/json",
  Authorization: `Token ${this.props.token}`,
};

if (requestType === "post") {
  await axios.post("http://127.0.0.1:8000/api/create/", postObj)
    .then(res => {
      if (res.status === 201) {
        this.props.history.push(`/`);
      }
    })
} else if (requestType === "put") {
  await axios.put(`http://127.0.0.1:8000/api/${articleID}/update/`, postObj)
    .then(res => {
      if (res.status === 200) {
        this.props.history.push(`/`);
      }
    })
}


};

  render() {
    return (
      <div>
        <Form
          onSubmit={event =>
            this.handleFormSubmit(
              event,
              this.props.requestType,
              this.props.articleID
            )
          }
        >
          <FormItem label="Title">
            <Input name="title" placeholder="Put a title here" />
          </FormItem>
          <FormItem label="Content">
            <Input name="content" placeholder="Enter some content ..." />
          </FormItem>
          <FormItem>
            <Button type="primary" htmlType="submit">
              {this.props.btnText}
            </Button>
          </FormItem>
        </Form>
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    token: state.token
  };
};

export default withRouter(connect(mapStateToProps)(CustomForm));

我希望这对某人有用。我使用 Django 作为后端

谢谢,这正是我的菜鸟错误。
2021-05-27 18:48:23

您可以将其window.location.href = '/somePath'用作最后的手段

它正在工作,但此方法正在刷新我的页面。
2021-06-14 18:48:23