即使在React Native中添加了数据后,flatlist也无法正确呈现数据?

时间:2020-05-07 06:24:36

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

我正在onMomentumScrollEnd的平面列表中添加数据,我从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);
      });
  }

即使正确添加数据后,您也可以查看列表中数据的呈现方式 enter image description here

1 个答案:

答案 0 :(得分:1)

从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,
          });
        }