【问题标题】:Redirect on button click in React在 React 中单击按钮时重定向
【发布时间】:2020-03-11 09:33:32
【问题描述】:

谁能告诉我重定向在反应中是如何工作的?

我来自 Angular 背景,正在尝试学习 React。

我有一个小型应用程序,我想通过单击按钮将用户重定向到 profile 组件。

这是一个非常基本的要求,但没有适当的文档可用(或者我找不到)。

任何帮助将不胜感激。

这是我的代码:

import { BrowserRouter, Route, Switch, Redirect } from "react-router-dom";

<BrowserRouter>
    <Switch>
      <Route path="/" exact render={props => <Index {...props} />} />
      <Route path="/login-page" exact render={props => <Login {...props} />} />
      <Route path="/profile-page" exact render={props => <Profile {...props} />} />
      <Route path="/dashboard" exact render={props => <Dashboard {...props} />} />
      <Redirect to="/" />
    </Switch>
  </BrowserRouter>,
<Button color='primary' onClick={e => this.viewProfile()}>View Profile</Button>

viewProfile = function () {
          console.log("clicked");
      }

【问题讨论】:

标签: reactjs react-router-dom


【解决方案1】:

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

class Test extends Component{
  constructor(props){
    super(props);
    this.state ={}
  }
  
  viewProfile = () => {
    const {history} = this.props;
    history.push('profile-page');
  }
}

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

class Test extends Component{
  constructor(props){
    super(props);
    this.state ={}
  }
  
  viewProfile = () => {
    const {history} = this.props;
    history.push('profile-page');
  }
  render(){
    return(
      <Button
        color='primary'
        onClick={() => this.viewProfile()}>
        View Profile
      />
    );
  }
}
export default withRouter(Test);

【讨论】:

    【解决方案2】:

    当您第一次学习新框架时,命名法很重要:)

    严格来说,redirect

    渲染&lt;Redirect&gt; 将导航到新位置。新位置将覆盖历史堆栈中的当前位置

    您想要的是导航到个人资料页面。有两种方法可以实现这一目标

    1. 通过 JSX Link

    2. 以编程方式使用history 对象。

    【讨论】:

      【解决方案3】:

      添加这个解决了我的问题。

      import { Redirect } from 'react-router'
      
      
            state = {
                redirect: false
               }
      
              const { redirect } = this.state;
      
              if (redirect) {
                return <Redirect to='/profile-page'/>;
              }
      
      
            viewProfile = function () {
                console.log("clicked");
                this.setState({ redirect: true })
            }
      
      

      感谢@tarzen chugh,@Good Samaritan 的回复

      【讨论】:

        【解决方案4】:

        这样做:-

        <Button color='primary' onClick={() => this.viewProfile()}>View Profile</Button>
        

        viewProfile= () => {
              return (
                <Redirect
                  to={{
                    pathname: "/profile-page",
                  }}
                />
              );
          };
        

        【讨论】:

          【解决方案5】:

          在这里你可以使用withRouter HOC 来做重定向。

          import { withRouter } from "react-router";
          
          class Component extends React.Component {
            viewProfile = function () {
               console.log("clicked");
               this.props.history.push('/main');
            }
          
            render(){
              return (
                 <Button color='primary' onClick={e => this.viewProfile()}>View Profile</Button>        
              )
            }
          
          }
          export default withRouter(Component);
          

          参考:https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md

          【讨论】:

            【解决方案6】:

            您可以调用useHistory() 挂钩进行导航。

            import { useHistory } from "react-router-dom";
            
            const yourComponent = () => {
              const history = useHistory();
              viewProfile = function() {
                history.push("/new-url");
              };
              return (
                <Button color="primary" onClick={viewProfile}>
                  View Profile
                </Button>
              );
            };
            

            如果您使用的是类组件,您可以将其包装withRouter() 以访问相同的history 对象。

            import React from "react";
            import { withRouter } from "react-router";
            
            class YourComponent extends React.Component {
              viewProfile = function() {
                const { history } = this.props;
                history.push("/new-url");
              };
            
              render() {
                return (
                  <Button color="primary" onClick={this.viewProfile}>
                    View Profile
                  </Button>
                );
              }
            }
            
            export default withRouter(YourComponent);
            

            【讨论】:

              【解决方案7】:

              使用 react-router-dom 中的 Link 组件:

              <Link to="/profile">View profile</Link>
              

              也可以查看docs,他们提供了很多示例

              【讨论】:

                【解决方案8】:

                React Router 带有一个Link 组件,可用于此目的。只需导入它,在 to 属性中设置目标,然后用它包装你的 Button

                import { Link } from "react-router-dom";
                
                <Link to='/profile-page'>
                   <Button color='primary' onClick={e => this.viewProfile()}>View Profile</Button>
                </Link>
                
                viewProfile = function () {
                    console.log("clicked");
                }
                

                看看 React Router docs,他们有很多有用的信息!

                【讨论】:

                  猜你喜欢
                  • 2021-05-15
                  • 2021-11-23
                  • 1970-01-01
                  • 2019-04-21
                  • 1970-01-01
                  • 2018-10-14
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多