React:添加按钮到组件,它导航到另一个页面



我想添加一个按钮到组件,点击后将导航到另一个页面。

目前我正在使用react 18.0.

下面是组件:

import React from 'react';
import EmployeeService from '../Services/EmployeeService';
import { AddEmployee } from '../Functions/AddEmployee';

class ListEmployeeComponent extends React.Component {

constructor(props) {
super(props)

this.state={
employees: []
}

}
componentDidMount() {
EmployeeService.getEmployees().then((res) => {
this.setState({employees:res.data});
});
}

render() {
return (
<div>
<h2 className='text-center'>Employee List</h2>
<div className='row'>
<button className='btn btn-primary' onClick={AddEmployee.bind(this)}>Add Employee</button>
</div>
<div className='row'>
<table className='table table-striped table-bordered'>
<thead>
<tr>
<th>Employee First Name</th>
<th>Employee Last Name</th>
<th>Employee Email Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{
this.state.employees.map(
employee =>
<tr key={employee.id}>
<td>{employee.firstName}</td>
<td>{employee.lastName}</td>
<td>{employee.email}</td>
</tr>
)
}
</tbody>
</table>
</div>

</div>
);
}
}
export default ListEmployeeComponent;

这是按钮:

import { useNavigate } from 'react-router';
export function AddEmployee(a, b) {
let navigate = useNavigate();
return (
navigate('http://localhost:3000/add-employee')
);
}

在附件的图片是一个错误,我得到当我按下按钮:错误

正如错误消息所说,React钩子需要在函数组件中使用。这里的钩子是useNavigate,你从一个普通函数调用它,因此会出现错误。如果您将注入navigate变量到AddEmployee函数中,您应该不会有问题。

export function AddEmployee(navigate, a, b) {
navigate(...);
}
// then within the component, do something akin to
const navigate = useNavigate();
AddEmployee(navigate, a, b)

好了,经过几个小时的寻找如何解决一个问题,我做了以下

我完全删除了添加员工功能。我从react-router-dom中导入了Link,并将Button更改为Link to

import {React,  Component} from 'react';
import {Link} from  'react-router-dom'
import EmployeeService from '../Services/EmployeeService';
class ListEmployeeComponent extends Component {
constructor(props) {
super(props)

this.state={
employees: []
}
}
componentDidMount() {
EmployeeService.getEmployees().then((res) => {
this.setState({employees:res.data});
});
}

render() {
return (
<div>
<h2 className='text-center'>Employee List</h2>
<div className='row'>
<Link to = '/add-employee' className='btn btn-primary' >Add Employee </Link>
</div>
<div className='row'>
<table className='table table-striped table-bordered'>
<thead>
<tr>
<th>Employee First Name</th>
<th>Employee Last Name</th>
<th>Employee Email Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{
this.state.employees.map(
employee =>
<tr key={employee.id}>
<td>{employee.firstName}</td>
<td>{employee.lastName}</td>
<td>{employee.email}</td>
</tr>
)
}
</tbody>
</table>
</div>

</div>
);
}
}
export default ListEmployeeComponent;

最新更新