reactjs 当以编程方式导航的URL已更改但UI仍然相同时,组件UI不更新

mwyxok5s  于 12个月前  发布在  React
关注(0)|答案(1)|浏览(108)

登录后,我试图重定向到特定的URL,但历史推送正在更改URL,但没有更新页面组件,我陷入了这个,组件UI不更新时,编程导航URL已更改,但UI仍然相同登录后,我试图重定向到特定的URL,但历史推送正在更改URL,但没有更新页面组件,我陷入了这个,组件UI不更新当编程导航URL已被更改,但UI仍然是相同的登录后,我试图重定向到特定的URL,但历史推送正在改变URL,但不更新页面组件,我坚持到这一点,组件UI不更新当编程导航URL已更改,但UI仍然相同登录后,我试图重定向到特定的URL,但历史推送正在更改URL,但不更新页面组件i我陷入了这个,组件UI不更新时,编程导航URL已更改,但UI仍然是相同的

import React, { Component } from "react";
import { Route } from "react-router";
import { BrowserRouter as Router, Routes } from "react-router-dom";
import { NavBar } from "./NavBar";
import { ShoppinCart } from "./ShoppinCart";
import { TaskQuantity } from "./TaskQuantity";
import { CustomersList } from "./CustomersList";
import { Login } from "./Login";
import { Dashboard } from "./Dashboard";
import { FourZeroFour } from "./FourZeroFour";
import history from "./history";

export class App extends Component {
  constructor(props) {
    super(props);
    this.state = { isLoggedIn: false };
  }

  render() {
    return (
      <Router history={history}>
        <NavBar
          isLoggedIn={this.state.isLoggedIn}
          UpdateLoginStatus={this.UpdateIslogedInStatus}
        />
        <div className="container">
          <Routes>
            <Route
              path="/"
              exact
              Component={(props) => (
                <Login
                  {...props}
                  UpdateIslogedInStatus={this.UpdateIslogedInStatus}
                />
              )}
            />
            <Route path="/Dashboard" exact element={<Dashboard />} />
            <Route path="/Customers" exact element={<CustomersList />} />
            <Route path="/cart" exact element={<ShoppinCart />} />
            <Route path="/Quantity" exact element={<TaskQuantity />} />
            <Route path="*" element={<FourZeroFour />} />
          </Routes>
        </div>
      </Router>
    );
  }

  UpdateIslogedInStatus = (status) => {
    this.setState({ isLoggedIn: status });
  };
}



import React, { Component } from "react";
import history from "./history";

export class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    return (
      <div>
        <div className="d-flex justify-content-center">
          <form className="pt-5">
            <div className="mb-3">
              <label htmlFor="exampleInputEmail1" className="form-label">
                Email address
              </label>
              <input
                type="email"
                className="form-control"
                id="exampleInputEmail1"
                aria-describedby="emailHelp"
                autoComplete="off"
                defaultValue={this.state.email}
                onChange={(event) => {
                  this.setState({ email: event.target.value });
                }}
              />
              <div id="emailHelp" className="form-text">
                We'll never share your email with anyone else.
              </div>
            </div>
            <div className="mb-3">
              <label htmlFor="exampleInputPassword1" className="form-label">
                Password
              </label>
              <input
                type="password"
                className="form-control"
                id="exampleInputPassword1"
                autoComplete="off"
                defaultValue={this.state.password}
                onChange={(evnet) => {
                  this.setState({ password: evnet.target.value });
                }}
              />
            </div>

            {this.state.message}

            <button
              type="button"
              className="btn btn-primary"
              onClick={this.onLoginClick}
            >
              Submit
            </button>
          </form>
        </div>
      </div>
    );
  }

  onLoginClick = async () => {
    let { history } = this.props;
    let response = await fetch(
      `http://localhost:5000/users?email=${this.state.email}&password=${this.state.password}`,
      {
        method: "GET",
      }
    );
    let body = await response.json();
    if (body.length > 0) {
      this.setState({
        message: (
          <div className="alert alert-success" role="alert">
            Logged In Successfully!
          </div>
        ),
      });
      this.props.UpdateIslogedInStatus(true);
      // history.push("/Dashboard");
      console.log(history);
    } else {
      this.setState({
        message: (
          <div className="alert alert-danger" role="alert">
            Please Enter Valid Credentials!
          </div>
        ),
      });
    }
  };
}
gstyhher

gstyhher1#

BrowserRouter在内部维护自己的历史引用,它不消耗任何history属性。要使用useNavigate钩子,您需要将React类组件转换为React函数组件。自React hooks were release in React 16.8 back in February 2019以来,所有意图和目的的React类组件都已被弃用。
登录

import React, { useState } from "react";
import { useNavigate } from 'react-router-dom'; // <-- import hook

const Login = ({ updateIsLoggedInStatus }) => {
  const navigate = useNavigate(); // <-- call hook and use navigate function

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [message, setMessage] = useState();

  const onLoginClick = async () => {
    const response = await fetch(
      `http://localhost:5000/users?email=${email}&password=${password}`,
      {
        method: "GET",
      }
    );
    const body = await response.json();
    if (body.length > 0) {
      setMessage(
        <div className="alert alert-success" role="alert">
          Logged In Successfully!
        </div>
      );
      updateIsLoggedInStatus(true);
      navigate("/Dashboard", { replace: true }); // <-- redirect to dashboard
    } else {
      setMessage(
        <div className="alert alert-danger" role="alert">
          Please Enter Valid Credentials!
        </div>
      );
    }
  };

  return (
    <div>
      <div className="d-flex justify-content-center">
        <form className="pt-5">
          <div className="mb-3">
            <label htmlFor="exampleInputEmail1" className="form-label">
              Email address
            </label>
            <input
              type="email"
              className="form-control"
              id="exampleInputEmail1"
              aria-describedby="emailHelp"
              autoComplete="off"
              defaultValue={this.state.email}
              onChange={(event) => setEmail(event.target.value)}
            />
            <div id="emailHelp" className="form-text">
              We'll never share your email with anyone else.
            </div>
          </div>
          <div className="mb-3">
            <label htmlFor="exampleInputPassword1" className="form-label">
              Password
            </label>
            <input
              type="password"
              className="form-control"
              id="exampleInputPassword1"
              autoComplete="off"
              defaultValue={this.state.password}
              onChange={(event) => setPassword(event.target.value)}
            />
          </div>

          {message}

          <button
            type="button"
            className="btn btn-primary"
            onClick={onLoginClick}
          >
            Submit
          </button>
        </form>
      </div>
    </div>
  );
};

App
Route组件没有任何exact属性,所有路由都 * 总是 * 完全匹配,因此应该删除它。Component prop应该是对React组件的引用,例如:Component={SomeComponent},但它实际上只适用于数据路由器,只需使用element属性并将组件作为ReactNode传递,例如。就像JSX。

export class App extends Component {
  constructor(props) {
    super(props);
    this.state = { isLoggedIn: false };
  }

  updateIsLoggedInStatus = (status) => {
    this.setState({ isLoggedIn: status });
  };

  render() {
    return (
      <Router>
        <NavBar
          isLoggedIn={this.state.isLoggedIn}
          UpdateLoginStatus={this.updateIsLoggedInStatus}
        />
        <div className="container">
          <Routes>
            <Route
              path="/"
              element={<Login updateIsLoggedInStatus={this.updateIsLoggedInStatus} />}
            />
            <Route path="/Dashboard" element={<Dashboard />} />
            <Route path="/Customers" element={<CustomersList />} />
            <Route path="/cart" element={<ShoppinCart />} />
            <Route path="/Quantity" element={<TaskQuantity />} />
            <Route path="*" element={<FourZeroFour />} />
          </Routes>
        </div>
      </Router>
    );
  }
}

相关问题