即使在 React Native 中附加数据后,Flatlist 也无法正确呈现数据?

Flatlist not rendering data properly even after getting data appended in React Native?

我在 onMomentumScrollEnd 的 flatlist 中添加数据,我从我的 REST 收到数据 API 仍然没有正确呈现数据。

        <FlatList
          onMomentumScrollEnd={() =>
            this.state.pageno <= this.state.maxPage
              ? this.getData('', 1, this.state.pageno + 1)
              : null
          }
          onEndReachedThreshold={0.5}
          data={this.state.responseData}
          ItemSeparatorComponent={this.ItemSeparatorLine}
          keyExtractor={(item, index) => index.toString()}
          showsVerticalScrollIndicator={true}
          renderItem={({item}) => (this.renderMyItem(item)} 
        />

这是追加数据的函数,在this.state.responseData

中完美获取数据
getData(text, apiType, pageno) {
    this.showLoader();
    this.setState({
      pageno: pageno,
      search: text,
      type: apiType,
    });

    let data = {
      pageNo: pageno,
      type: apiType,
      search: text,
      sortedBy: '',
      sortedIn: 'DESC',
      filter: {},
    };

    const headers = {
      'X-Auth-Token': this.state.token,
      'Content-Type': 'application/json',
    };

    console.log(data);

    axios
      .post(PIDataApi, data, {headers: headers})
      .then(response => {
        this.setState({
          isLoading: false,
        });
        if (response.data.status != 2000) {
          Toast.show(response.data.error.errorMessage, Toast.SHORT);
        } else {
          if (response.data.data.resource != null) {
            let historyData = response.data.data.resource;
            console.log('api response:', historyData);
            if (this.state.pageno > 1) {
              this.setState({
                responseData: [...this.state.responseData, historyData],
                maxPage: response.data.data.maxPage,
              });
              console.log('responseData : ', this.state.responseData);
            } else {
              this.setState({
                responseData: historyData,
                maxPage: response.data.data.maxPage,
              });
            }
          } else {
            Toast.show(response.data.data.message, Toast.SHORT);
          }
        }
      })

      .catch(error => {
        console.error(error);
      });
  }

您可以看到数据在列表中的呈现方式,即使在正确附加数据之后也是如此

您从 axios 请求中获得的响应以数组的形式向您发送 historyData,但是您直接将其设置为状态而不传播

此外,当您根据之前的状态更新状态时,请务必使用函数式 setState

  if (this.state.pageno > 1) {
          this.setState(prevState => ({
            responseData: [...prevState.responseData, ...historyData], // spread historyData here
            maxPage: response.data.data.maxPage,
          }));
        } else {
          this.setState({
            responseData: historyData,
            maxPage: response.data.data.maxPage,
          });
        }