React Router不会根据状态重定向

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

在代码中,它到达isRegistered函数,我知道这是因为我有它的console.log状态。注册状态等于true。因此,基于代码,它应该重定向到/ login但不是。

import React from 'react'
import "./Register.css";
import {BrowserRouter as Route, Redirect, Link} from 'react-router-dom'
const initialUser = {
  username: "",
  email: "",
  password: "",
  password2: "",
  name: ""
}
class Register extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      user: initialUser,
      registered: ''
    };
  }

  onUsernameChange = event => {
    this.setState({ username: event.target.value });
  };
  onNameChange = event => {
    this.setState({ name: event.target.value });
  };

  onEmailChange = event => {
    this.setState({ email: event.target.value });
  };

  onPasswordChange = event => {
    this.setState({ password: event.target.value });
  };
  onPassword2Change = event => {
    this.setState({ password2: event.target.value });
  };
  isRegistered() {
    const { registered } = this.state;
    console.log(registered, 'here', this.state)
    if (registered) {
      return (
          <Redirect to='/login' />
      )
    }
  }
  onRegister = () => {
    fetch("http://localhost:3000/register", {
      method: "post",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        name: this.state.name,
        email: this.state.email,
        username: this.state.username,
        password: this.state.password,
        password2: this.state.password2
      })
    })
    .then(res => res.json())
    .then(data => {
      console.log(data.isRegistered);
      if (data.isRegistered) {
        this.setState({registered: true})
        this.isRegistered();
      }
    })
  };

  render() {
      return <div className="login-page">
          <div className="form">
            <form className="login-form">
              <input type="text" placeholder="name" onChange={this.onNameChange} />
              <input type="text" placeholder="username" onChange={this.onUsernameChange} />
              <input type="text" placeholder="email" onChange={this.onEmailChange} />
              <input type="password" placeholder="password" onChange={this.onPasswordChange} />
              <input type="password" placeholder="confirm password" onChange={this.onPassword2Change} />
              <button className="bluecolor" onClick={this.onRegister}>
                Register
              </button>
              <p className="message">
                Have an account? <a href="/login">Login</a>
              </p>
            </form>
          </div>
        </div>;
  }
}

export default Register;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

它一直到达isRegistered()中的if语句。所以我认为它是重定向组件是错误的,但我无法弄清楚我的生活。

//更新这是我现在拥有的内容

import React from 'react'
import "./Register.css";
import {BrowserRouter as Route, Redirect, withRouter} from 'react-router-dom'
const initialUser = {
  username: "",
  email: "",
  password: "",
  password2: "",
  name: ""
}
class Register extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      user: initialUser,
      registered: ''
    };
  }

  onUsernameChange = event => {
    this.setState({ username: event.target.value });
  };
  onNameChange = event => {
    this.setState({ name: event.target.value });
  };

  onEmailChange = event => {
    this.setState({ email: event.target.value });
  };

  onPasswordChange = event => {
    this.setState({ password: event.target.value });
  };
  onPassword2Change = event => {
    this.setState({ password2: event.target.value });
  };
  isRegistered() {
    const { registered } = this.state;
    console.log(registered, 'here', this.state)
    if (registered) {
      this.props.history.push('/login')
    }
}
  onRegister = () => {
    fetch("http://localhost:3000/register", {
      method: "post",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        name: this.state.name,
        email: this.state.email,
        username: this.state.username,
        password: this.state.password,
        password2: this.state.password2
      })
    })
    .then(res => res.json())
    .then(data => {
      console.log(data.isRegistered);
      if (data.isRegistered) {
        this.setState({registered: true})
        this.isRegistered();
      }
    })
  };

  render() {
      return <div className="login-page">
          <div className="form">
            <form className="login-form">
              <input type="text" placeholder="name" onChange={this.onNameChange} />
              <input type="text" placeholder="username" onChange={this.onUsernameChange} />
              <input type="text" placeholder="email" onChange={this.onEmailChange} />
              <input type="password" placeholder="password" onChange={this.onPasswordChange} />
              <input type="password" placeholder="confirm password" onChange={this.onPassword2Change} />
              <button className="bluecolor" onClick={this.onRegister}>
                Register
              </button>
              <p className="message">
                Have an account? <a href="/login">Login</a>
              </p>
            </form>
          </div>
        </div>;
  }
}

export default withRouter(Register);

这是主要的App.js

import React, { Component } from 'react';
import RegisterFull from "./Components/Register/RegisterFull";
import LoginFull from "./Components/Login/LoginFull";
import HomeFull from "./Components/Home/HomeFull";
import FullContact from "./Components/Contact/FullContact";
import './App.css';
import './Components/flex.css'
import {BrowserRouter as Router, Route} from "react-router-dom";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      signedIn: false
    }
  }
  loginUser = () => {
    this.setState({signedIn: true})
  }
  render() {
    return (
      <Router>
        <div>
        <Route exact={true} path='/' component={HomeFull}/>
        <Route path='/contact' component={FullContact} />
        <Route path='/login' component={LoginFull} />
        <Route path='/register' component={RegisterFull} />
        <Route path='/about' component={HomeFull} />        
        </div>
      </Router>
      
    )
  }
}

export default App;
javascript reactjs
3个回答
0
投票

您可以对代码进行一些改进。这是我的建议。 you don't need to bind anything。您正在使用最新的React。我怎么知道?你在做onUsernameChange = evnet => {}而不是onUsernameChange(event){}。整体而言@Sakhi Mansoor是对的。

import React from "react";
import "./Register.css";
import {
  BrowserRouter as Route,
  withRouter,
  Redirect,
  Link
} from "react-router-dom";

const initialUser = {
  username: "",
  email: "",
  password: "",
  password2: "",
  name: ""
};

class Register extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      user: initialUser,
      registered: ""
    };
  }

  handleChange = event => {
    this.setState({
      user: {
        ...this.state.user,
        [event.target.name]: event.target.value
      }
    });
  };

  isRegistered = () => {
    const { registered } = this.state;
    console.log(registered, "here", this.state);
    if (registered) {
      this.props.history.push("/login");
    }
  };

  onRegister = event => {
    event.preventDefault();
    fetch("http://localhost:3000/register", {
      method: "post",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(this.state.user)
    })
      .then(res => res.json())
      .then(data => {
        console.log(data.isRegistered);
        if (data.isRegistered) {
          this.setState({ registered: true });
          this.isRegistered();
        }
      });
  };

  render() {
    return (
      <div className="login-page">
        <div className="form">
          <form className="login-form" onSubmit={this.onRegister}>
            <input
              type="text"
              placeholder="name"
              name="name"
              value={this.state.user.name}
              onChange={this.handleChange}
            />
            <input
              type="text"
              placeholder="username"
              name="username"
              value={this.state.user.username}
              onChange={this.handleChange}
            />
            <input
              type="text"
              placeholder="email"
              name="email"
              value={this.state.user.email}
              onChange={this.handleChange}
            />
            <input
              type="password"
              placeholder="password"
              name="password"
              value={this.state.user.password}
              onChange={this.handleChange}
            />
            <input
              type="password"
              placeholder="confirm password"
              name="password2"
              value={this.state.user.password2}
              onChange={this.handleChange}
            />
            <button className="bluecolor" type="submit">
              Register
            </button>
            <p className="message">
              Have an account? <a href="/login">Login</a>
            </p>
          </form>
        </div>
      </div>
    );
  }
}

export default withRouter(Register);

2
投票

您不能通过在组件生命周期或方法中调用另一个方法来返回这样的渲染中的Redirect元素。

你需要使用提供历史道具的withRouter HOC包装你的组件。

import {BrowserRouter as Route,, withRouter, Redirect, Link} from 'react-router-dom'


export default withRouter(Register);

如果您想以编程方式导航:

isRegistered = () => {
const { registered } = this.state;
console.log(registered, 'here', this.state)
if (registered) {
 this.props.history.push('/login)
 }
}

0
投票

这是一个如何重定向按钮单击的简单示例。希望这可能对您有所帮助

import React, { Component } from "react";
import { BrowserRouter,Route,Switch } from 'react-router-dom'
class App extends Component {
  render() {
    return (
      <BrowserRouter>
      <Switch>
      <Route path="/" exact component={Sample}/>
      <Route path="/test" exact render={()=>(<p>Test</p>)}/>
      </Switch>
      </BrowserRouter>
    )
  }
}
class Sample extends React.Component {
  constructor(props) {
    super(props)
    this.Click = this.Click.bind(this) // you need to bind the method
  }
  Click() {
    this.props.history.push('/test');
  }
  render() {
    return(
      <button onClick={this.Click}>Click</button>
    )
  }
}
export default App;
热门问题
推荐问题
最新问题