如何在Reactjs的新的react-router-dom中使用重定向


131

我正在使用最新版本的react-router模块,名为react-router-dom,该模块已成为使用React开发Web应用程序时的默认模块。我想知道在POST请求后如何进行重定向。我一直在编写此代码,但是在请求之后,什么都没有发生。我在网上查看过,但是所有数据都是关于React Router的先前版本的,而关于最后一个更新的则不是。

码:

import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { Redirect } from 'react-router'

import SignUpForm from '../../register/components/SignUpForm';
import styles from './PagesStyles.css';
import axios from 'axios';
import Footer from '../../shared/components/Footer';

class SignUpPage extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      errors: {},
      client: {
        userclient: '',
        clientname: '',
        clientbusinessname: '',
        password: '',
        confirmPassword: ''
      }
    };

    this.processForm = this.processForm.bind(this);
    this.changeClient = this.changeClient.bind(this);
  }

  changeClient(event) {
    const field = event.target.name;
    const client = this.state.client;
    client[field] = event.target.value;

    this.setState({
      client
    });
  }

  async processForm(event) {
    event.preventDefault();

    const userclient = this.state.client.userclient;
    const clientname = this.state.client.clientname;
    const clientbusinessname = this.state.client.clientbusinessname;
    const password = this.state.client.password;
    const confirmPassword = this.state.client.confirmPassword;
    const formData = { userclient, clientname, clientbusinessname, password, confirmPassword };

    axios.post('/signup', formData, { headers: {'Accept': 'application/json'} })
      .then((response) => {
        this.setState({
          errors: {}
        });

        <Redirect to="/"/> // Here, nothings happens
      }).catch((error) => {
        const errors = error.response.data.errors ? error.response.data.errors : {};
        errors.summary = error.response.data.message;

        this.setState({
          errors
        });
      });
  }

  render() {
    return (
      <div className={styles.section}>
        <div className={styles.container}>
          <img src={require('./images/lisa_principal_bg.png')} className={styles.fullImageBackground} />
          <SignUpForm 
            onSubmit={this.processForm}
            onChange={this.changeClient}
            errors={this.state.errors}
            client={this.state.client}
          />
          <Footer />
        </div>
      </div>
    );
  }
}

export default SignUpPage;

1
Redirect看起来像JSX,而不是JS。
elmeister

您可以为您提供整个组件代码吗?
KornholioBeavis'Apr

是的,我正在使用JSX。好吧,也许我需要澄清一下。POST请求位于发出请求的REACT组件内。
maoooricio

@KornholioBeavis,当然,现在您可以看到完整。我使用expressjs制作服务器,不知道您是否需要此数据
maoooricio

您可以验证您是否从axios.post获得了回调响应吗?另外,为什么不使用Async函数而无需在任何地方等待?
KornholioBeavis

Answers:


197

您必须使用setState设置一个属性,该属性将呈现<Redirect>您的render()方法内部。

例如

class MyComponent extends React.Component {
  state = {
    redirect: false
  }

  handleSubmit () {
    axios.post(/**/)
      .then(() => this.setState({ redirect: true }));
  }

  render () {
    const { redirect } = this.state;

     if (redirect) {
       return <Redirect to='/somewhere'/>;
     }

     return <RenderYourForm/>;
}

您还可以在官方文档中看到一个示例:https : //reacttraining.com/react-router/web/example/auth-workflow


就是说,我建议您将API调用放在服务之内。然后,您可以使用该history对象以编程方式进行路由。这就是与redux集成的工作方式。

但是我想您有这样做的理由。


1
@sebastian sebald您的意思是put the API call inside a service or something什么?
andrea-f

1
在组件内部具有这样的(异步)API调用将使测试和重用变得更加困难。通常最好创建一个服务,然后在中使用它(例如)componentDidMount。甚至更好的是,创建一个“包装”您的API 的HOC
塞巴斯蒂安·塞巴尔德

6
请注意,您必须在文件的开头包含重定向,才能使用它:从“ react-router-dom”导入{Redirect}
Alex

3
是的,在幕后Redirect打电话history.replace。如果要访问history对象,请使用withRoutet/ Route
塞巴斯蒂安·塞巴尔德

1
react-router> = 5.1现在包含了钩子,因此您可以const history = useHistory(); history.push("/myRoute")
TheDarkIn1978 '19

34

在我看来,这里有一个小例子,作为对标题的回应,我和官方都认为这很复杂。

您应该知道如何转换es2015以及使服务器能够处理重定向。这是表达的片段。与此相关的更多信息可以在这里找到。

确保将其放在所有其他路线的下方。

const app = express();
app.use(express.static('distApp'));

/**
 * Enable routing with React.
 */
app.get('*', (req, res) => {
  res.sendFile(path.resolve('distApp', 'index.html'));
});

这是.jsx文件。请注意,最长的路径是最先到达的,而get则更通用。对于最一般的路线,请使用精确属性。

// Relative imports
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';

// Absolute imports
import YourReactComp from './YourReactComp.jsx';

const root = document.getElementById('root');

const MainPage= () => (
  <div>Main Page</div>
);

const EditPage= () => (
  <div>Edit Page</div>
);

const NoMatch = () => (
  <p>No Match</p>
);

const RoutedApp = () => (
  <BrowserRouter >
    <Switch>
      <Route path="/items/:id" component={EditPage} />
      <Route exact path="/items" component={MainPage} />          
      <Route path="/yourReactComp" component={YourReactComp} />
      <Route exact path="/" render={() => (<Redirect to="/items" />)} />          
      <Route path="*" component={NoMatch} />          
    </Switch>
  </BrowserRouter>
);

ReactDOM.render(<RoutedApp />, root); 

1
这并不总是有效。如果您从home/hello> 重定向,home/hello/1但是转到home/hello并点击Enter,则不会第一次重定向。任何想法为什么?
海象

我建议您尽可能使用“ create-react-app”,并遵循react-router的文档。使用“ create-react-app”对我来说一切正常。我无法将自己的React应用程序适应新的react-router。
Matthis Kohli


8

由于使用了useHistory()钩子,因此React Router v5现在允许您使用history.push()进行简单重定向:

import { useHistory } from "react-router"

function HomeButton() {
  let history = useHistory()

  function handleClick() {
    history.push("/home")
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  )
}

6

尝试这样的事情。

import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { Redirect } from 'react-router'

import SignUpForm from '../../register/components/SignUpForm';
import styles from './PagesStyles.css';
import axios from 'axios';
import Footer from '../../shared/components/Footer';

class SignUpPage extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      errors: {},
      callbackResponse: null,
      client: {
        userclient: '',
        clientname: '',
        clientbusinessname: '',
        password: '',
        confirmPassword: ''
      }
    };

    this.processForm = this.processForm.bind(this);
    this.changeClient = this.changeClient.bind(this);
  }

  changeClient(event) {
    const field = event.target.name;
    const client = this.state.client;
    client[field] = event.target.value;

    this.setState({
      client
    });
  }

  processForm(event) {
    event.preventDefault();

    const userclient = this.state.client.userclient;
    const clientname = this.state.client.clientname;
    const clientbusinessname = this.state.client.clientbusinessname;
    const password = this.state.client.password;
    const confirmPassword = this.state.client.confirmPassword;
    const formData = { userclient, clientname, clientbusinessname, password, confirmPassword };

    axios.post('/signup', formData, { headers: {'Accept': 'application/json'} })
      .then((response) => {
        this.setState({
          callbackResponse: {response.data},
        });
      }).catch((error) => {
        const errors = error.response.data.errors ? error.response.data.errors : {};
        errors.summary = error.response.data.message;

        this.setState({
          errors
        });
      });
  }

const renderMe = ()=>{
return(
this.state.callbackResponse
?  <SignUpForm 
            onSubmit={this.processForm}
            onChange={this.changeClient}
            errors={this.state.errors}
            client={this.state.client}
          />
: <Redirect to="/"/>
)}

  render() {
    return (
      <div className={styles.section}>
        <div className={styles.container}>
          <img src={require('./images/lisa_principal_bg.png')} className={styles.fullImageBackground} />
         {renderMe()}
          <Footer />
        </div>
      </div>
    );
  }
}

export default SignUpPage;

很有效!,谢谢你。这是另一种方法。
maoooricio

您不应该在组件文件中发出HTTP请求
Kermit_ice_tea

您能否共享“ ../../register/components/SignUpForm”中导入SignUpForm的内容?我正在尝试从中学习。虽然在我的情况,我用的是终极版的形式
TEMI“玩转”贝洛

3

或者,您可以使用withRouter。你可以访问history对象的属性和最近<Route>matchwithRouter高阶组件。withRouter将通更新matchlocationhistory道具给被包装的成分时,它呈现。

import React from "react"
import PropTypes from "prop-types"
import { withRouter } from "react-router"

// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props

    return <div>You are now at {location.pathname}</div>
  }
}
// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation)

要不就:

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

const Button = withRouter(({ history }) => (
  <button
    type='button'
    onClick={() => { history.push('/new-location') }}
  >
    Click Me!
  </button>
))

1

您可以为此目的编写一个临时文件并编写一个方法调用重定向,下面是代码:

import React, {useState} from 'react';
import {Redirect} from "react-router-dom";

const RedirectHoc = (WrappedComponent) => () => {
    const [routName, setRoutName] = useState("");
    const redirect = (to) => {
        setRoutName(to);
    };


    if (routName) {
        return <Redirect to={"/" + routName}/>
    }
    return (
        <>
            <WrappedComponent redirect={redirect}/>
        </>
    );
};

export default RedirectHoc;

1
"react": "^16.3.2",
"react-dom": "^16.3.2",
"react-router-dom": "^4.2.2"

为了导航到另一个页面(在我的情况下是关于页面),我安装了prop-types。然后将其导入相应的组件中,并使用this.context.router.history.push('/about')进行导航。

我的代码是

import React, { Component } from 'react';
import '../assets/mystyle.css';
import { Redirect } from 'react-router';
import PropTypes from 'prop-types';

export default class Header extends Component {   
    viewAbout() {
       this.context.router.history.push('/about')
    }
    render() {
        return (
            <header className="App-header">
                <div className="myapp_menu">
                    <input type="button" value="Home" />
                    <input type="button" value="Services" />
                    <input type="button" value="Contact" />
                    <input type="button" value="About" onClick={() => { this.viewAbout() }} />
                </div>
            </header>
        )
    }
}
Header.contextTypes = {
    router: PropTypes.object
  };

0

要导航到另一个组件,您可以使用 this.props.history.push('/main');

import React, { Component, Fragment } from 'react'

class Example extends Component {

  redirect() {
    this.props.history.push('/main')
  }

  render() {
    return (
      <Fragment>
        {this.redirect()}
      </Fragment>
    );
   }
 }

 export default Example

1
React发出警告:Warning: Cannot update during an existing state transition (such as within 渲染). Render methods should be a pure function of props and state.
Robotron

0

导航到另一个组件的最简单解决方案是(示例通过单击图标导航到邮件组件):

<MailIcon 
  onClick={ () => { this.props.history.push('/mails') } }
/>

0

另外,您可以使用React条件渲染。

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

class UserSignup extends Component {
  constructor(props) {
    super(props);
    this.state = {
      redirect: false
    }
  }
render() {
 <React.Fragment>
   { this.state.redirect && <Redirect to="/signin" /> }   // you will be redirected to signin route
}
</React.Fragment>
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.