首页 > 解决方案 > 为什么 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:到目前为止,我还没有配置任何数据库,因为我需要在调用数据库之前检查组件是否按预期工作

标签: javascriptreactjs

解决方案


如果你把它放在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 上的用户名时,您可以在Profile组件中通过this.props.match.params.url. 这解决了你的两个问题。现在对于导航栏,您可以将其放在 Instructor 组件中或创建一个 InstructorRouter 组件并将导航栏放在那里以及更多路由逻辑。这样,您只能限制讲师资料内的导航栏。现在针对刷新后用户名丢失的情况。如果您在 url 上有用户名,即使在页面刷新后您也会保留它。但如果您经常需要,最好将其保存在 localStorage 中。但是,如果您的网址不会改变或无关紧要,您可以继续使用它。


推荐阅读