【问题标题】:React redirect using react-router-dom not working使用 react-router-dom 的 React 重定向不起作用
【发布时间】:2018-05-21 01:57:02
【问题描述】:

我想在 ajax 响应后重定向到主页我使用了 Redirect 但不起作用

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

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

我使用带有更新版本的 react-router-dom。但它不会将我重定向到主页并且控制台中没有错误

【问题讨论】:

  • 您只能在渲染方法中使用&lt;Redirect /&gt;。如果您想以编程方式重定向,则必须使用this.props.history.push。请注意,要使历史对象在您的道具中可用,您的组件必须被路由到,或者被包裹在 withRouter HOC 中。
  • 是的。但我不知道如何修改我的路由 js 文件。请编辑我的路由 js 文件
  • 需要修改的不是您的 route.js 文件,而是您的 ajax 处理程序(以及它所在的组件)。我已经告诉你需要做什么了,继续自己尝试,如果你仍然无法弄清楚,请更新你的代码。

标签: reactjs


【解决方案1】:

您应该使用 history.push。请参阅下面的示例:

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

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

组件

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>
  }
}

【讨论】:

  • 在哪里可以找到 history.js 文件
  • history.js只有2行,请看我上面的代码。您可以单独创建它。
  • 这里我需要从 npm 安装历史记录
猜你喜欢
  • 2021-07-27
  • 2021-02-11
  • 2020-04-23
  • 2021-07-24
  • 2018-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-05
相关资源
最近更新 更多