reactjs - 如何从 ReactJS 中的项目列表中删除前端的项目
问题描述
我正在尝试从我从 REST API 动态获取的项目列表中删除一个项目。出于某种原因,onDelete
当我按下“搜索”按钮时,我的函数被调用,而不是在我想删除特定列表项时单独调用。不知道为什么。
class Users extends Component {
constructor(props) {
super(props);
this.state = {
searchValue: '',
users: []
};
}
handleOnChange = event => {
this.setState({ searchValue: event.target.value });
};
handleSearch = () => {
this.makeApiCall(this.state.searchValue);
};
onDelete(e) {
console.log('why is this being called?');
}
makeApiCall = async searchInput => {
let res = await axios(
`https://zuul-stage.whatifops.com/v1/user/phone/${searchInput}`
);
this.setState({ users: res.data });
};
render() {
return (
<div>
<input
name='text'
type='text'
placeholder='Search'
onChange={event => this.handleOnChange(event)}
value={this.state.searchValue}
/>
<button onClick={this.handleSearch}>Search</button>{' '}
{this.state.users ? (
<div>
{this.state.users.map((user, index) => (
<div key={user.id}>
<Row>
<Col lg={2} style={{ maxWidth: '9.7%' }}>
<Button
color='danger'
style={{ paddingTop: 12, paddingBottom: 12 }}
onClick={this.onDelete()}
>
<i className='fa fa-trash'></i> Delete
</Button>
</Col>
<Col lg={10}>
<ListGroup>
<ListGroupItem>
<strong>Email:</strong> {user.email}
<strong>Phone:</strong> {user.phone}
</ListGroupItem>
</ListGroup>
</Col>
</Row>
</div>
))}
</div>
) : (
<p>Try searching for a user</p>
)}
</div>
);
}
}
export default Users;
我使用的 onDelete 函数是
onDelete(e){
let id = e.target.id;
let updatedUsers = this.users.filter(user=>user.id!=id)
this.setState({users:updatedUsers })
}
但是我收到一个关于用户未定义的错误,并且它没有被单独调用 onClick。不知道我做错了什么,我认为这将是一件简单的事情,但我正在努力!
解决方案
问题是正在调用 onDelete(除非更改以下内容,否则将自动调用)
改变:
{this.onDelete()}
至:
{() => this.onDelete()}
或到(一旦 onDelete 被正确界定):
{this.onDelete}
推荐阅读
- android - 如何在 Flutter 中使用 GestureDetector 隐藏 appBar?
- javascript - 在 JavaScript 中保持矩形的纵横比
- python - 需要了解如何在 python 中从一个目录开始导入模块
- rust - 混合选择!Rust 中的异步调用
- uml - 我应该在我的用例图中包含系统作为参与者吗?
- sql - SQL获取日期之间的行数
- r - 警告消息:要替换的项目数不是替换长度的倍数
- javascript - Javascript 引号索引器
- r - 拉取后如何在 R 中编辑 CSV 文件中的数据?
- google-chrome-extension - Node.js 导入/导出和 chrome/opera/firefox 扩展。2020年的情况