首页 > 解决方案 > 如何在 React 中使用 history.push 导航

问题描述

我可以将我的组件名称添加到:例如:this.props.history.push(<Sample/>)

我有一个关于在此添加路径的想法:this.props.history.push("/Sample").

或者如何将其导航到我的组件:

.catch((error) => {
    console.log("error", error);
    this.setState({
        finishedStep: false,
    });
    this.props.history.push("<Sample/>");
});

如果完成的步骤是false,我想将其导航到我的<Sample>组件。

标签: javascriptreactjstypescript

解决方案


假设您已经为<Sample />Component 配置了相应的路由。

react-router-dom

安装 - react-router-dom

npm install --save react-router-dom

例子:

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

class YourComponent extends React.Component {
   handleSubmit = (user) => {
     saveUser(user).then(() =>
     this.props.history.push('/dashboard')
     )).catch((error) => {
      console.log("error", error);
      this.setState({
        finishedStep: false,
      });
      this.props.history.push("/Sample");
     })
   }      
   render() {
    return (
      <div>
        <Form onSubmit={this.handleSubmit} />
      </div>
    )
  }
}

export default withRouter(YourComponent)

您可以不使用的另一种方法react-router-dom是。

render() {
    if (this.state.finishedStep === false) {
      return <Redirect to='/Sample' />
    }

    return (
      <div>
        <Form onSubmit={this.handleSubmit} />
      </div>
    )
  }

推荐阅读