为什么刷新页面后ReactJS组件消失

时间:2019-06-20 08:17:55

标签: javascript reactjs

在用户单击Instructor Profile中的login按钮之后,我试图显示Instructor Login Form组件

在刷新页面之前一切正常,刷新后User Profile组件消失

这是用户单击login

后页面的屏幕截图

这是我刷新以上页面后的屏幕截图:

如您在第二张屏幕截图中所见,组件已消失(显示欢迎使用个人资料

这就是我的InstructorLoginForm的样子

import React, { Component } from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import InstructorProfile from "./instructor-profile";
import InstructorLoginFormComponent from "./instructor-login-form-component";

export default class InstructorLoginForm extends Component {
  constructor(props) {
    super(props);

    this.state = {
      username: "",
      password: ""
    };

    this.onChangeUsername = this.onChangeUsername.bind(this);
    this.onChangePassword = this.onChangePassword.bind(this);
    this.handleOnClick = this.handleOnClick.bind(this);
  }

  onChangeUsername(e) {
    this.setState({
      username: e.target.value
    });
  }

  onChangePassword(e) {
    this.setState({
      password: e.target.value
    });
  }

  handleOnClick(e) {
    e.preventDefault();
    this.props.history.push(`/instructor/${this.state.username}`);
  }

  render() {
    return (
      <Router>
        <Switch>
          <Route
            exact
            path="/login"
            render={props => (
              <InstructorLoginFormComponent
                {...props}
                username={this.state.username}
                onChangeUsername={this.onChangeUsername}
                password={this.state.password}
                onChangePassword={this.onChangePassword}
                handleOnClick={this.handleOnClick}
              />
            )}
          />

          <Route
            path={"/instructor/:username"}
            render={props => (
              <InstructorProfile {...props} username={this.state.username} />
            )}
          />
        </Switch>
      </Router>
    );
  }
}

这就是我的InstructorLoginFormComponent的样子:

import React, { Component } from "react";
import { Link } from "react-router-dom";

export default class InstructorLoginFormComponent extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount(){
    console.log(this.props);
  }

  handleOnClick(e){
      e.preventDefault();
      console.log("Hello");
  }

  render() {
    return (
      <div className="container h-100" style={{ marginTop: 100 }}>
        <div className="d-flex justify-content-center h-100">
          <div className="user_card bg-dark">
            <div className="d-flex justify-content-center">              
            </div>
            <div
              className="d-flex justify-content-center form_container"
              style={{ marginTop: 0 }}
            >
              <form>
                <div className="input-group mb-3">
                  <div className="input-group-append">
                    <span className="input-group-text bg-info">
                      <i className="fa fa-user" />
                    </span>
                  </div>
                  <input
                    value={this.props.username}
                    onChange={this.props.onChangeUsername}
                    type="text"
                    name="username"
                    className="form-control input_user"
                    placeholder="username"
                  />
                </div>
                <div className="input-group mb-2">
                  <div className="input-group-append">
                    <span className="input-group-text bg-info">
                      <i className="fa fa-lock" />
                    </span>
                  </div>
                  <input
                    value={this.props.password}
                    onChange={this.props.onChangePassword}
                    type="password"
                    name="passwordbutton"
                    className="form-control input_user"
                    placeholder="password"
                  />
                </div>
                <div className="form-group">
                  <div className="custom-control custom-checkbox">
                    <input
                      type="checkbox"
                      className="custom-control-input"
                      id="customControlInline"
                    />
                    <label
                      className="custom-control-label"
                      htmlFor="customControlInline"
                      style={{ color: "#ffffff" }}
                    >
                      Remember me
                    </label>
                  </div>
                </div>
              </form>
            </div>

            <div className="d-flex justify-content-center mt-3 login_container">
              <Link
                to={`/instructor/${this.props.username}`}                
                type="button"
                className="btn login_btn bg-info">
                Login
              </Link>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

这是我的InstructorProfile的样子:

import React, { Component } from "react";

export default class InstructorProfile extends Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>          
        <h1>Welcome to the profile {this.props.username}</h1>
      </div>
    );
  }
}

有人可以给我一个解决方案吗?而且我需要摆脱上面的导航栏,该导航栏每次都显示,与加载哪个组件无关紧要。我该怎么办?

  

PS:到目前为止,我尚未配置任何数据库,因为在对数据库进行任何调用之前,我需要检查组件是否按预期工作

2 个答案:

答案 0 :(得分:0)

如果将其放入codesandbox中并在此处提供链接,将会更容易。因此,其他人可以测试并推荐您解决方案。我看到的问题之一是您的组件结构不可伸缩。例如,用户名和密码应是登录组件的一部分,而路由应在不同的组件中。

import React, { Component } from 'react'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

const App = () => (
  <Router>
    <Switch>
      <Route exact path="/login" component={LoginForm} />
      <Route path="/instructor/:username" component={InstructorProfile} />
    </Switch>
  </Router>
)

这样做,您正在将路由置于父级,现在每个组件都有其自己的用途和状态。您应该从LoginForm处理用户名,密码登录等。一旦成功,您就可以将用户重定向到(“ / instructor / username”)。并且当使用url上的用户名进行重定向时,您可以通过this.props.match.params.url个人资料组件中进行访问。这可以解决您的两个问题。现在,对于导航栏,您可以将其放置在Instructor组件内部或创建InstructorRouter组件,然后将导航栏放置在其中,以及更多的路由逻辑。这样,您仅将导航栏限制在教师个人资料内。现在,对于刷新后丢失用户名的情况。如果您在url上拥有用户名,即使页面刷新后也将保留它。但是,好主意是在需要时将其保留在localStorage中。但是,如果您的网址不会更改或无关紧要,则可以使用它。

答案 1 :(得分:0)

当您加载InstructorLoginForm时,localhost:3000/instructor/admin似乎根本不呈现。从不同的网址访问应用时,请检查您的应用是否正确运行。将一些日志记录添加到InstructorLoginForm

  render() {
    console.log('hello, I am InstructorLoginForm');
    return (
      <Router>
      .....
刷新页面后,

this.state.username为空。您应该改用以下代码:

     <Route
        path={"/instructor/:username"}
        render={props => (
          <InstructorProfile {...props} username={props.match.params.username} />
        )}
      />