使用<switch>和<redirect>在页面之间进行路由会返回主页-ReactJS

时间:2019-02-05 08:33:26

标签: javascript reactjs react-router

此任务的目标是将页面重定向到下一页。基本上,当用户扫描会员卡时,必须出现一个弹出窗口,通知他一切正常,然后将其重定向到下一页。到现在为止,我了解了扫描的状态,并出现了弹出窗口,但是它不会将我重定向到下一页。我不知道该怎么解决这个问题?到目前为止,这是我的代码:

模块

AppComponent

HomeJS.js -我的超时功能

import React, { Component } from 'react';
import { BrowserRouter as Router } from 'react-router-dom'
import { Redirect, Switch } from 'react-router'
import Route from 'react-router-dom/Route';
import BarcodeReader from 'react-barcode-reader';
import SPage from '../pages/SelectionPage'

HomeJS.js *-其余代码*

class Home extends Component {

  constructor() {
    super();
    this.state = {
      okRedirect: true,
      modalOK: false
    }
    this.handleScan = this.handleScan.bind(this)
  }

  handleScan(data) {
    console.log('barcode is' + data);
    this.setState({
      modalOK: true
    })

    setTimeout( function() {
      console.log('setTimeOut OK');
      this.setState({ okRedirect: true });
      console.log('state redirect: ' + this.state.okRedirect);

    }.bind(this) , 3000)
  }

2 个答案:

答案 0 :(得分:0)

使用Redirect代替Route转到您想要的页面。

<Route exact path="/" render={() => (this.state.okRedirect &&
          <Route path="/SPage" component={SPage}/>) }/>

或者您可以为Route定义/SPage并执行Redirect

答案 1 :(得分:0)

实际上并非必须使用<Redirect/>。我的问题的简单答案是:

class Home extends Component {

  constructor() {
    super();
    this.state = {
      okRedirect: false,
      modalOK: false
    }

    this.handleScan = this.handleScan.bind(this)
  }

  handleScan(data) {

    this.setState({
      modalOK: true
    })

    setTimeout( function() {

      this.setState({ okRedirect: true });


    }.bind(this) , 3000)
  }

  render() {

    if (this.state.okRedirect) {
      console.log('State is changed');
      return (

        <SelectionPage/>
      );

    }