如何在基于 class 的组件中使用 react-router-dom-v6 从一个页面导航到另一个页面?

how to navigate from one page to other page using react-router-dom-v6 in class-based component?

我在我的 WebApp 中使用 React-router-dom-V6 通过 Class Based Component 进行导航,我想从一个页面导航到另一个页面,我该如何实现?在功能组件中有一个名为 useNavigate() 的 Hook,如何在 class 组件中导航?

您可以在 class 个组件中使用 Navigate 个组件进行导航。

import * as React from "react";
import { Navigate } from "react-router-dom";

class LoginForm extends React.Component {
  state = { user: null, error: null };

  async handleSubmit(event) {
    event.preventDefault();
    try {
      let user = await login(event.target);
      this.setState({ user });
    } catch (error) {
      this.setState({ error });
    }
  }

  render() {
    let { user, error } = this.state;
    return (
      <div>
        {error && <p>{error.message}</p>}
        {user && (
          <Navigate to="/dashboard" replace={true} />
        )}
        <form onSubmit={event => this.handleSubmit(event)}>
          <input type="text" name="username" />
          <input type="password" name="password" />
        </form>
      </div>
    );
  }
}

React Router v6 推荐 React hooks. As we can read in official docs :

React Router v6 makes heavy use of React hooks, so you'll need to be on React 16.8 or greater before attempting the upgrade to React Router v6.

我找到了一个方法,但请不要在真正的应用程序中使用,而是使用带有 react-router 的功能组件-dom-v6,

import React, { Component } from "react";
import { connect } from "react-redux";
import { Navigate, useNavigate } from "react-router-dom";
import "./EmployeeList.css";
import { styled } from "@mui/material/styles";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell, { tableCellClasses } from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Paper from "@mui/material/Paper";
import Button from "@mui/material/Button";
import Stack from "@mui/material/Stack";
import { deleteEmployee } from "../redux/employee/employeeAction";

const StyledTableCell = styled(TableCell)(({ theme }) => ({
  [`&.${tableCellClasses.head}`]: {
    backgroundColor: theme.palette.common.black,
    color: theme.palette.common.white,
  },
  [`&.${tableCellClasses.body}`]: {
    fontSize: 14,
  },
}));

const StyledTableRow = styled(TableRow)(({ theme }) => ({
  "&:nth-of-type(odd)": {
    backgroundColor: theme.palette.action.hover,
  },
  //hide last border
  "&:last-child td, &:last-child th": {
    border: 0,
  },
}));

class EmployeeList extends Component {
  constructor(props) {
    super(props);
    this.state ={
      redirect : false,
      data : {}
    }
  }

  componentDidMount(){
    this.setState({
      redirect : false,
      data : {}
    })
  }

  deleteUser = (id) => {
    this.props.deleteEmploy(id);
  };

  onPressEdit = (item) => {
   // Navigate("/editemployee", { replace: true, state: { ...item } });
    // return <Navigate to="/editemployee" replace={true} />
    this.setState({
      redirect: true,
      data : {
        ...item
      }
    })
  };

  render() {
    if(this.state.redirect) {
    return <Navigate to="/editemployee" state={this.state.data}/>
    }

    return(
      <div className="container">
        <TableContainer component={Paper}>
          <Table sx={{ minWidth: 700 }} aria-label="customized table">
            <TableHead>
              <TableRow>
                <StyledTableCell align="center">Name</StyledTableCell>
                <StyledTableCell align="center">Email</StyledTableCell>
                <StyledTableCell align="center">Number</StyledTableCell>
                <StyledTableCell align="center"></StyledTableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {this.props.employeeList.map((item) => {
                return (
                  <StyledTableRow key={item.id}>
                    <StyledTableCell align="center">
                      {item.name}
                    </StyledTableCell>
                    <StyledTableCell align="center">
                      {item.email}
                    </StyledTableCell>
                    <StyledTableCell align="center">
                      {item.number}
                    </StyledTableCell>
                    <StyledTableCell align="center">
                      <Stack direction="row" spacing={2}>
                        <Button
                          variant="outlined"
                          onClick={() => this.deleteUser(item.id)}
                        >
                          Delete
                        </Button>
                        <Button
                          variant="contained"
                          onClick={() => this.onPressEdit(item)}
                        >
                          Edit
                        </Button>
                      </Stack>
                    </StyledTableCell>
                  </StyledTableRow>
                );
              })}
            </TableBody>
          </Table>
        </TableContainer>
      </div>
    );
  }
}

const mapStateToProps = (state, ownProps) => {
  return { employeeList: state.employee.employee };
};
const mapDispatchAToProps = (dispatch) => ({
  deleteEmploy: (id) => dispatch(deleteEmployee(id)),
});

export default connect(mapStateToProps, mapDispatchAToProps)(EmployeeList);