REACT-NATIVE:Flatlist 不会根据道具更改进行更新

REACT-NATIVE: Flatlist doesn't update on props change

我有一个项目页面,在该页面上呈现与该项目相关的评论的平面列表,我遇到的问题是当我更改项目时,使用新道具(itemId)的 api 调用没有' t happen and the comments from the previous item are rendered.

我确定新的 itemId 正在传递到屏幕,因为其他一切都发生了变化(名称、图片、描述...)

您到达商品页面的方式是通过商店页面呈现商品图片列表(我在商品页面上传递了呈现商品所需的所有道具)

我确实注意到,当我在项目页面上然后按返回返回商店页面,然后单击另一个项目时,项目页面在更新之前显示前一个项目的数据半秒,但是列表永远不会更新,它会一直使用旧的 itemId 进行调用。 我使用 fetch 来获取列表,我也尝试过使用 axios,结果相同。

 componentDidMount() {
    this._isMounted = true;

    const { navigation } = this.props;

this.focusListener = navigation.addListener('didFocus', async () => {
    await fetch("https://api..." + navigation.getParam('itemId'))
            .then(response => response.json())
            .then((responseJson) => {
                this.setState({
                    loading: false,
                    dataSource: responseJson
                })
                console.log("response Comments:" + JSON.stringify(responseJson));
                console.log('the state of item id -->', this.props.navigation.getParam('itemId'))
            });
   }
}

当我 console.log 时,我得到了正确的 itemId,但似乎调用发生在它收到新道具之前...

我对 React Native 和一般编码比较陌生,所以如果我需要更清楚,请告诉我。

感谢您的帮助!

我遇到了类似的问题。这是因为 FlatListprops 保持不变。虽然对于个人 renderItem,它正在改变,但 FlatList 组件不知道这一点。

要解决这个问题,您可以使用 extraData prop.

因此,如果您像 extraData={this.props} 一样将 extraData prop 设置为 FlatList,这将在父组件的任何 prop 更改时强制重新加载列表。