反应:如何重定向

问题描述 投票:0回答:1

我是React的初学者,正在实现一个函数,在该按钮上单击render方法,然后转到foo函数。在该功能中,我将用户名和密码发送到服务器。

如果用户名和密码正确,它将返回一个JSON对象,例如

{"Result":1,"Cookie":"COOKIE!!!"}

如果结果为1,我正在尝试将其重定向到我制作的另一个类组件(Flood),可以有人帮助我吗

我尝试在渲染之后和返回之前重定向它,但出现错误

 Error: Invariant failed: You should not use <Redirect> outside a <Router> 
import React from 'react';
import './style.scss';
import LoginImage from './LoginImage.png'
import Button from 'react-bootstrap/Button'
import Form from 'react-bootstrap/Form'
import {Redirect, Router} from 'react-router-dom'
//import Logfailed from './Logfailed'
import Flood from './Flood'

class UserLogin extends React.Component {
  constructor(props) {
    super(props);
    this.state = {userName:'', password:'', act:'l', flag:0, txt:''};
    this.handleChange1 = this.handleChange1.bind(this);
    this.handleChange2 = this.handleChange2.bind(this);
    this.handleClick = this.handleClick.bind(this);
  }

   async handleClick(e) {
    const url = 'http://52.8.557.164/user'
    const data = {username:this.state.userName, password:this.state.password, action:this.state.act};
    try {
        const response = await fetch(url, 
        {
            method: 'POST',
            body: JSON.stringify(data),
            headers: {
                'Content-Type': 'application/json'
            },
        });
        const json = await response.json();
      if(json['Result'] === 1) {
        this.setState({flag: 1, txt:''});
      }
      else {

         this.setState({flag:2, txt:'Wrong username and Password'}); 
      }
        console.log('Success', JSON.stringify(json));
      console.log(json['Cookie']);
    } catch (error) {
        console.error('Error', error);
    }

 }

 handleChange1(e) {
  this.setState({userName: e.target.value})
 }
 handleChange2(e) {
  this.setState({password: e.target.value})
 }


render() {
  if (this.state.flag === 1) {
        return <Redirect to='/Flood' />
    }
    return (
        <div className = 'outer-container' ref={this.props.containerRef}> 
            <div className = 'header'> Login </div>
            <div className="content">
      <div className="image">
              <img src={LoginImage} />
      </div>

            <Form className = 'form'>
        <Form.Group controlId="formBasicEmail" className = 'form-group'>
          <Form.Label style={{marginTop: '90px'}}>Username</Form.Label>
          <Form.Text className="text-muted" htmlFor="username"></Form.Text>
          <input type="text" value = {this.state.userName} name="username" placeholder="username" onChange={this.handleChange1}/>
        </Form.Group>
        <Form.Group controlId="formBasicPassword" className = 'form-group'>
        <Form.Label>Password</Form.Label>
        <Form.Text className="text-muted" htmlFor="password"></Form.Text>
          <input type="password" value = {this.state.password}  name="password" placeholder="password" onChange={this.handleChange2} />
          <br></br>
          <span>{this.state.txt}</span>
        </Form.Group>
        </Form>
            </div>
        <div className="footer">
                <Button variant="outline-primary" size="lg" onClick={this.handleClick} className="btn" block>
                    Login
                </Button>
          </div>
      </div>
    );
}   
}

export default UserLogin;
import React from 'react';
class Flood extends React.Component {
  constructor(props) {
    super(props)
  }

    render() {
        return (
            <h1>gg</h1>
            )}
}

export default Flood;
javascript reactjs react-redux react-router react-dom
1个回答
0
投票
import { withRouter } from 'react-router-dom'

然后在导出时包装您的组件/类

export default withRouter(yourComponent);

好,现在回到问题所在:要重定向,您只需将某些内容推送到历史记录对象

history.push('/redirect-location');
© www.soinside.com 2019 - 2024. All rights reserved.