简体   繁体   English

使用react-router-dom的React重定向不起作用

[英]React redirect using react-router-dom not working

I want to redirect to home page after ajax response I used Redirect but not working 我想在使用Ajax响应后重定向到主页,但无法正常工作

$.ajax({
    method: 'post',
    data: {req: data2},
    url: baseUrl+'sentOtp',
    success: function(response){
        console.log(response);
        if (response.status === "success") {
            return <Redirect to="/" />;
        }
    }
});

Route.js Route.js

ReactDOM.render(
 <Router>
  <Switch>
    <Route exact path="/" component={App} />
    <Route path="/pdeals/:BrandName/all/:Type" component={BrowseFeedDeals} />
    <Route path="/login" component={Register} />
  </Switch>
</Router>, document.getElementById('root'));
registerServiceWorker();

I used react-router-dom with updated version.but it doesn't redirect me to the home page and no errors in console 我使用了具有更新版本的react-router-dom,但它不会将我重定向到主页,并且控制台中没有错误

You should use history.push. 您应该使用history.push。 See my example below: 请参阅下面的示例:

index.js index.js

    import React, { Component } from 'react'
    import { render } from 'react-dom'
    import { Router, Route, BrowserHistory as hashHistory, Switch } from 'react-router-dom'
    import './style.css'
    import history from './history.js'

    import Home from './routes/home.js'

    class App extends Component {
      constructor() {
        super()
        this.state = {
        }
      }

      render() {
        return (
          <Router history={history}>
            <Switch>
              <Route exact path='/' component={Home}/>
            </Switch>
          </Router>
        )
      }
    }

render(<App />, document.getElementById('root'));

history.js history.js

import createHistory from 'history/createBrowserHistory'
export default createHistory()

Component 零件

import React from 'react'
import styled from 'styled-components'
import history from '../../history.js'


export default class NavBar extends React.Component {

  linkClick() {
    history.push('/')
  }

  render() {
    return <div onClick={this.linkClick}>
    </div>
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM