我正在使用MERN堆栈在Web应用程序上工作,该应用程序显示具有其名称,电子邮件和电话号码的客户表。我还没有实现Redux,但是我正在使用'uuid'来补充表中的数据,直到可以设置redux存储。到目前为止,我已经显示了列表,并向列表中添加了一个客户端,但工作正常,但是我讨厌使用讨厌的删除按钮。
这是当前的ClientTable组件
import React, { Component } from "react";
import { Table, Container, Button } from "reactstrap";
import { connect } from "react-redux";
import {
getClients,
addClient,
editClient,
deleteClient,
} from "../actions/clientActions";
import PropTypes from "prop-types";
const renderClient = (clients, index, id) => {
return (
<tr key={index}>
<td>
<Button
className="remove-btn"
color="danger"
size="sm"
onClick={() => {
this.setState((state) => ({
clients: state.clients.filter((client) => client.id !== id),
}));
}}
>
×
</Button>
</td>
<td>{clients.name}</td>
<td>{clients.email}</td>
<td>{clients.number}</td>
</tr>
);
};
class ClientTable extends Component {
componentDidMount() {
this.props.getClients();
}
onDeleteClick = (id) => {
this.props.deleteClient(id);
};
render() {
const { clients } = this.props.client;
// const { clients } = this.state;
return (
<Container id="listContainer">
<Table
id="listTable"
className="table-striped table-bordered table-hover"
dark
>
<tr class="listRow">
<thead id="tableHeader">
<tr>
<th id="listActions">Actions</th>
<th id="listName">Name</th>
<th id="listEmail">Email</th>
<th id="listNumber">Number</th>
</tr>
</thead>
<tbody class="listRow">{clients.map(renderClient)}</tbody>
</tr>
</Table>
</Container>
);
}
}
ClientTable.propTypes = {
getClients: PropTypes.func.isRequired,
client: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
client: state.client,
});
export default connect(mapStateToProps, {
getClients,
deleteClient,
addClient,
})(ClientTable);
这是引起我问题的代码位
<Button
className="remove-btn"
color="danger"
size="sm"
onClick={() => {
this.setState((state) => ({
clients: state.clients.filter((client) => client.id !== id),
}));
}}
>
×
</Button>
当我单击“删除”按钮时,我不断得到TypeError:无法读取未定义的属性'setState'
我知道错误是因为'this'没有绑定任何东西,但是我不确定如何在onClick事件中绑定它,甚至可能绑定它。我只是迷失了如何解决这个问题。 (我对React还是很陌生的)。
如果有人有任何想法,将不胜感激!
在功能组件中没有setState
,甚至没有this
您所期望的。
相反,您可以使用useState
挂钩进行状态管理,如下所示:
const renderClient = (clients, index, id) => {
const [clients, setClients] = useState([]);
// component code ...
}
然后使用setClients
代替this.setState
将完成工作。
我建议阅读文档中的how to use the state hook。
我希望这能解释!