在React中单击按钮重定向

时间:2019-11-15 09:02:08

标签: reactjs react-router-dom

任何人都可以告诉我重定向如何在反应中起作用吗?

我来自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");
      }

8 个答案:

答案 0 :(得分:2)

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

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

也请查看docs,它们提供了很多示例

答案 1 :(得分:1)

反应路由器带有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,他们有很多有用的信息!

答案 2 :(得分:0)

您可以调用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);

答案 3 :(得分:0)

添加此内容解决了我的问题。

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 :(得分:0)

第一次学习新框架时,术语很重要:)

严格来说redirect

  

渲染<Redirect>将导航到新位置。新位置将覆盖历史记录堆栈中的当前位置

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

  1. 通过JSX Link

  2. 使用history对象进行编程。

答案 5 :(得分:0)

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);

答案 6 :(得分:-1)

您可以在此处使用p = ['www.sample.de/fl/autor/xxx', 'www.sample.de/fl/autor/xxx', 'www.sample.de/fl/autor/xxx', 'www.temp.de/thema/xxx', 'www.temp.de/thema/xxx', 'www.sample.de/fl/autoor/xxx', 'www.temp.de/theema/xxx', ] filters = ['/autor/', '/thema/' ] fil = [] for sbl in p: flag = False for i in filters: if i in sbl: flag = True if not flag: fil.append(sbl) fil #['www.sample.de/fl/autoor/xxx', 'www.temp.de/theema/xxx'] HOC进行重定向。

withRouter

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

答案 7 :(得分:-1)

这样做:-

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

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