如何在有状态组件的React Router 5.1.2中使用history.push('path')?

时间:2019-12-19 02:45:02

标签: reactjs react-router react-router-dom

如何在有状态组件(类组件)的React Router 5.1.2中使用history.push('path')?

我找到了,但这是无状态组件的解决方案

import { useHistory } from "react-router-dom";

function App() {
  let history = useHistory();
}

谢谢:-) 亚当

3 个答案:

答案 0 :(得分:10)

在使用React Router v5时,我遇到了同样的问题。 当尝试通过以下方式以编程方式更改路线时,

this.props.history.push({
    pathname: `/target-path`,
    state: variable_to_transfer
});

this.props.history 未定义

这是我的React Router v5解决方案。

import React, { Component } from "react";
import { withRouter } from 'react-router-dom';

class MyClass extends Component {
    routingFunction = (param) => {
        this.props.history.push({
            pathname: `/target-path`,
            state: param
        });
    }
    ...
}
export default withRouter(MyClass);

这里是reference article。 希望它可以帮助您节省时间。

答案 1 :(得分:0)

这是在基于状态/类的组件中使用this.props.history.push('/...')导航到其他组件的方法。

const BasicExample = () => (
  <Router>
    <div>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/about">About</Link>
        </li>
      </ul>

      <hr />

      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
    </div>
  </Router>
);
const About = () => (
  <div>
    <h2>About</h2>
  </div>
);
class Home extends React.Component {
  handleClick = e => {
    this.props.history.push("/about");
  };
  render() {
    return (
      <div>
        <h2>Home</h2>

        <button onClick={this.handleClick}>Click to navigate about page</button>
      </div>
    );
  }
}

Live Demo

答案 2 :(得分:-2)

只需将所有内容包裹在 中并使用 创建一个对象文字,例如:

import { BrowserRouter } from 'react-router-dom';
...
...
return(
   <BrowserRouter>
      ...
      ...
   </BrowserRouter>
)

并在函数中使用:

import { useHistory } from 'react-router-dom';
...
...
const history = useHistory();

function handlePush() {
...
history.push('/url');
...
}

这对你来说应该是一种锻炼。 乐于帮助。 ? 来自 RTTSS。