React-router TypeError:_this.props.history未定义

Man*_*umi 16 reactjs react-router

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

编译时显示错误,

TypeError: _this.props.history is undefined
Run Code Online (Sandbox Code Playgroud)

这是我的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')
);
Run Code Online (Sandbox Code Playgroud)

这是我的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;
Run Code Online (Sandbox Code Playgroud)

Gui*_*ume 19

这是因为React Router在4.0.0开始时发生了变化.您现在应该在使用时BrowserRouterreact-router-dom包中使用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')
);
Run Code Online (Sandbox Code Playgroud)

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

另请注意,如果您使用多个Route元素,则必须按照本答案中的Switch说明使用a .


Sh *_*lav 14

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

1) 组件作为子组件

<Route path="/path">
 <MyComponent/>
</Route>
Run Code Online (Sandbox Code Playgroud)

2)组件作为“组件”道具

<Route path="/path" component={MyComponent}>
</Route>
Run Code Online (Sandbox Code Playgroud)

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

更新

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

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

const componentClassWithHistory = withRouter(ChildComponent);
export {componentClassWithHistory as ChildComponent};
Run Code Online (Sandbox Code Playgroud)

或默认导出

export default withRouter(ChildComponent)
Run Code Online (Sandbox Code Playgroud)

或打字稿

const componentClassWithHistory = (withRouter(ChildComponent as any) as any);
export {componentClassWithHistory as ChildComponent};
Run Code Online (Sandbox Code Playgroud)

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

希望它可以帮助某人。


小智 6

你在用npm吗?我在package.json中遇到了"react-router":"^ 4.0.0"的问题.将其更改为"react-router":"^ 3.0.2"解决了我的问题.

  • 当你按照官方教程和第1课不起作用时,这不是一个好兆头:> (13认同)

aks*_*hir 6

我的 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));
Run Code Online (Sandbox Code Playgroud)

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


Ben*_*yam 5

你可以window.location.href = '/somePath'作为最后的手段