React Native Flatlist 在上拉时不刷新数据

这是我的帖子页面代码,它在加载时从我的 API 获取帖子标题,这很完美。问题是,一旦它被加载,如果一个新帖子被添加到 API 并且我拉起来刷新它不会得到新帖子,即使我的 onRefresh 函数工作,因为我可以在其中触发警报。


我可以在 API 中获取新帖子以在加载后显示的唯一方法是重新加载应用程序本身。


componentDidMount() {

    this.fetchData()

  }


  constructor(props) {

    super(props);

    this.state = {

      refreshing: true,

      data: []

    };

  }


fetchData = () => {

    const url = 'myAPIurl';

    fetch(url)

      .then(res => {

        return res.json()

      })

      .then(res => {

        const arrayData = [...this.state.data, ...res]

        this.setState({

          data: arrayData,

          refreshing: false

        });

      })

      .catch(error => {

        console.log(error);

        this.setState({ refreshing: false });

      });

  };



handleRefresh = () => {

  this.setState(

    {

      refreshing: true

    },

    () => {

      this.fetchData();

      alert('Pulled Up to Refresh');

    }

  );

};



  render() {

    return (


<View>

      <FlatList

        refreshControl={

          <RefreshControl

            refreshing={this.state.refreshing}

            onRefresh={this.handleRefresh}

          />

        }

        horizontal={false}

        data={this.state.data}

        keyExtractor={item => item.id}

        renderItem={({ item }) =>

    <View>

          <Text>{item.title.rendered}</Text>

     </View>

        }

      />

</View>

    );

  }

}

当我拉起刷新时,我收到此警告:两个具有相同密钥的孩子。键应该是唯一的。这很奇怪,因为每个帖子 ID 都是唯一的。即使有这个警告,API 中的新帖子也不会显示,除非我重新加载应用程序。


HUH函数
浏览 211回答 1
1回答

小唯快跑啊

更改您的handleRefresh功能,如下所示:handleRefresh = () => {this.setState({&nbsp; refreshing: true,&nbsp; data:[]},() => {&nbsp; this.fetchData();&nbsp; alert('Pulled Up to Refresh');&nbsp; }&nbsp;);};
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript