删除数据后,平板列表不会重新呈现

时间:2020-06-14 21:48:36

标签: reactjs react-native react-native-flatlist

sortedData道具中删除数据时,我的本机平面列表未重新呈现。我尝试使用extraData道具来强制重新渲染,但这没有用。当我删除元素时,出现空白行。

handleRemove = (title) => {
    // const start = this.state.people.slice(0, index);
    // const end = this.state.people.slice(index + 1);
    // this.setState({
    //   people: start.concat(end),
    // });
    const filteredData = this.state.sortedData.filter(
      (item) => item.title !== title
    );
    this.setState({ sortedData: filteredData });
  };

  render() {
    const { sortedData } = this.state;

    return (
      <FlatList
        data={sortedData}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item, index }) => (
          <LeaderboardEntry
            song={item}
            handler={this.handler}
            onRemove={() => this.handleRemove(item.title)}
          />
        )}
      />
    );
  }

1 个答案:

答案 0 :(得分:2)

您应该像下面这样

 var newSortedData = [...this.state.sortedData];
    newSortedData.splice(index, 1);
    this.setState({
      sortedData: newSortedData,
    });

原因是,即使您正在更新状态,该状态指向状态中的同一数组,因此您也需要使用散布运算符,该操作会创建一个新数组,进而导致重新渲染。

更新 使用过滤器删除项目 您的单位列表应更改为

onRemove={() => this.handleRemove(item.title,index)}

句柄删除功能的逻辑

handleRemove = (title,index) => {
    const filteredData = this.state.sortedData.filter(
      (item,index) => item.index !== in
    );
    this.setState({ sortedData: filteredData });
  };

这里完全不需要title参数,您也可以将其删除。