首页 > 解决方案 > 如何从 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>&nbsp; Delete
                    </Button>
                  </Col>
                  <Col lg={10}>
                    <ListGroup>
                      <ListGroupItem>
                        <strong>Email:</strong> {user.email} &nbsp; &nbsp;
                        <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。不知道我做错了什么,我认为这将是一件简单的事情,但我正在努力!

标签: reactjsaxios

解决方案


问题是正在调用 onDelete(除非更改以下内容,否则将自动调用)

改变:

{this.onDelete()}

至:

{() => this.onDelete()}

或到(一旦 onDelete 被正确界定):

{this.onDelete}

推荐阅读