返回了新组件,但先前的组件在ReactJs中保持不变

时间:2019-05-10 06:52:12

标签: reactjs

登录后会返回一个新组件,但是登录组件和Home组件都可以在页面上看到。我需要返回没有登录组件的Home Componenet。我是React的新手,仍在尝试了解React中的返回和路线。

这是我的页面组件,它基于this.state.redirect1返回登录名或主页。

    import React, { Component } from 'react';
    import { Redirect } from 'react-router-dom';
    import '../../App.css';
    import Login from '../Login';
    import Home from '../Home';
    import Header from './Header';
    import Footer from './Footer';


    class Pages extends Component {
      constructor(props) {
        super(props)

        this.state = {
          redirect: false,
        }

  }
  handleClick() {
    this.state.redirect = true;
    console.log(this.state.redirect);
  }
  changeRedirect =() =>{
    this.state.redirect = true;
    console.log(this.state.redirect);
    this.forceUpdate()

  }
  renderRedirect = () => {
    if(this.props.redirect1){
      return <Home/>
    }
    else{
      return <Login/>
    }
  }

  render() {

    return (

      <div className="mh-100 PgWidth">
      {this.renderRedirect()}
      </div>
    )
  }
}
export default Pages

以下是我的登录名,首页和应用程序组件

Login.js

import React, { Component } from 'react'
import Axios from 'axios';
import Pages from './common/Pages'
import { Redirect } from 'react-router-dom';

class Login extends Component {


    constructor(props) {
        super(props)

        this.state = {
            username: '',
            password: '',
            redirect: false
        }
    }

    handleUsername = (event) => {
        this.setState({
            username: event.target.value
        })
    }

    handlePassword = (event) => {
        this.setState({
            password: event.target.value
        })
    }
    renderRedirect = () => {
        if (this.state.redirect) {
            console.log("from render redirect");
            return <Pages redirect1={this.state.redirect} />
        }
    }


    formSubmitHandler = event => {
        let formdata = new FormData();
        formdata.append("username", this.state.username);
        formdata.append("password", this.state.password);
        Axios.post("/auth/local",{
            "name":this.state.username,
            "password": this.state.password
           })
            .then(res => {
                if (res) {
                    console.log(res);
                    this.setState({ redirect: true });


                }


            })
        event.preventDefault() // used to keep the form data as entered even after the submit
    }

    render() {

        const { username, password } = this.state
        return (

            <div className="p-5">
            { this.renderRedirect() }
                <h3>Sign-In</h3>
                <form onSubmit={this.formSubmitHandler}>
                    <div className="form-group row">
                        <label htmlFor="inputEmail3" className="col-sm-2 col-form-label">Username</label>
                        <div className="col-sm-10">
                            <input type="text" value={username} onChange={this.handleUsername}
                                className="form-control" id="inputEmail3" placeholder="Username" />
                        </div>
                    </div>
                    <div className="form-group row">
                        <label htmlFor="inputPassword3" className="col-sm-2 col-form-label">Password</label>
                        <div className="col-sm-10">
                            <input type="password" value={password} onChange={this.handlePassword}
                                className="form-control" id="inputPassword3" placeholder="Password" />
                        </div>
                    </div>

                    <div className="form-group row">
                        <div className="col-sm-2">Checkbox</div>
                        <div className="col-sm-10">
                            <div className="form-check">
                                <input className="form-check-input" type="checkbox" id="gridCheck1" />
                                <label className="form-check-label" htmlFor="gridCheck1">
                                    Example checkbox
                                </label>
                            </div>
                        </div>
                    </div>
                    <div className="form-group row">
                        <div className="col-sm-10">
                            <button type="submit" onClick={this.formSubmitHandler} className="btn btn-primary">Sign in</button>
                        </div>
                    </div>
                </form>

            </div>

        )
    }
}

export default Login

Home.js

import React, { Component } from 'react'
import '../App.css';


export class Home extends Component {

  componentDidMount(){
    console.log("home component mount");
  }



  render() {
    return (
      <div>
        <h1>The page has been routed</h1>
      </div>
    );
  }
}

export default Home

App.js

import React, { Component } from 'react';
import './App.css';
import Header from './components/common/Header';
import Footer from './components/common/Footer';
import Pages from './components/common/Pages';

class App extends Component {
  render() {
    return (

      <div className="App container-fluid bg-light w-75">
      <div className="row justify-content-md-center">
        <div className="col m-0 p-0">
          <Header/>
            <div className="">
            <Pages/>
            </div>
          <Footer/>
        </div>
      </div>
    </div>
    );
  }
}

export default App;

3 个答案:

答案 0 :(得分:2)

问题在这一行:

{ this.renderRedirect() }

一旦重定向为true,它将首先呈现“首页”,然后呈现“登录”组件。

您遇到的问题的解决方法是:仅在Page组件中管理重定向布尔,然后将一个函数更新为Login组件,以更新其值并根据该值决定该组件。

更改:

1-在页面组件中定义的redirect: false

2-更改其在Pages组件中的值的函数:

updateValue = (value) => {
  this.setState({ redirect: true })
}

3-将功能传递给登录组件:

renderRedirect = () => {
  if(this.props.redirect1) {
    return <Home/>
  }
  else{
    // =====> here
    return <Login updateValue={this.updateValue} />
  }
}

4-成功登录后,调用此函数并呈现Home Component:

formSubmitHandler = event => {
  event.preventDefault();

  let formdata = new FormData();
  formdata.append("username", this.state.username);
  formdata.append("password", this.state.password);

  Axios.post("/auth/local",{
    "name":this.state.username,
    "password": this.state.password
  })
  .then(res => {
    if (res) {
       // =======> here
       this.props.updateValue(true)
    }
  })
}

5-从登录组件中删除此行:

{ this.renderRedirect() }

当前代码问题:

您正在使用状态变量管理登录会话,因此刷新页面后,它将再次显示登录页面而非主页。因此最好将值存储在localStorage中,并在页面组件中读取其值以确定redirect的初始值。

建议:

与其使用boolean来决定路线/组件,不如使用react-router来更好地构造/管理应用程序。

答案 1 :(得分:1)

尝试在渲染中将其返回:

    import React, { Component } from 'react';
    import { Redirect } from 'react-router-dom';
    import '../../App.css';
    import Login from '../Login';
    import Home from '../Home';
    import Header from './Header';
    import Footer from './Footer';


    class Pages extends Component {
      constructor(props) {
        super(props)

        this.state = {
          redirect: false,
        }

  }
  handleClick() {
    this.state.redirect = true;
    console.log(this.state.redirect);
  }
  changeRedirect =() =>{
    this.state.redirect = true;
    console.log(this.state.redirect);
    this.forceUpdate()

  }

  render() {

  if(this.props.redirect){
    return (
      <div className="mh-100 PgWidth">
        <Home/>
      </div>
    )
  } else {
    return (
      <div className="mh-100 PgWidth">
        <Login/>
      </div>
    )
  }
}
export default Pages;

答案 2 :(得分:0)

您可以这样做

<div className="mh-100 PgWidth">
  {this.props.redirect1&&<Home/>}
  {!this.props.redirect1&&<Login />}
</div>

但是,最好的方法是使用React路由器并管理全局React状态