首页 > 解决方案 > React Native 中的屏幕不会自动刷新

问题描述

async componentDidMount () {         
        this._isMounted = true;
        await this.showPosts();
  }

  componentDidUpdate () {
        this.showPosts();   
  }

  showPosts = async () => {    
    try {    
    var userID = await AsyncStorage.getItem('userID');

    fetch(strings.baseUri+"getPostWithUserID", {
        method: 'POST',
        headers: {
           Accept: 'application/json',
           'Content-Type': 'application/json'
        },
        body: JSON.stringify({ 
            "user_id": userID
        })
        })
        .then((response) => response.json())
        .then((responseJson) => {

        let jsonObj = JSON.parse(JSON.stringify(responseJson));

        if (jsonObj.status=="true") {

            this.setState({ 
                data: responseJson.data, 
                imageSrc: responseJson.data.imgSrc, 
            });

        } 
        else {
            if (this._isMounted) {
                this.setState({show: false});
            }
        }  

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

  }

  componentWillUnmount () {
    this._isMounted = false;
  }

showPosts是我的函数,它获取数据并将其显示到平面列表中。

 <FlatList 
            data={this.state.data}
            keyExtractor={(index) => index.toString()}
            renderItem={ ({item,index}) => this._renderItem(item,index) }
            extraData={[ this.state.checked, this.state.data ]}
 />
  1. 现在,当我上传一篇帖子并返回我的主屏幕时,它会调用showPosts并通过再次重新加载应用程序在我的模拟器上检查它,它会向我显示该帖子。
  2. 现在,当我上传另一个帖子并返回主屏幕时,我不需要在模拟器中重新加载我的应用程序,但我componentDidUpdate会被调用并自动刷新屏幕并向我显示新帖子。

我的问题是,当主屏幕上的帖子为零时,为什么我必须再次重新加载(通过多次按 R 重新加载)我的应用程序。我希望在我上传第一篇文章时自动更新我的屏幕。只有在超过 1 个帖子的情况下,屏幕才会自动更新。

PS - 我也试过onRefresh()了,对我的问题没有帮助。

标签: javascriptandroidreactjsreact-nativereact-native-flatlist

解决方案


利用forceUpdate()

请检查此链接:https ://reactjs.org/docs/react-component.html#forceupdate


推荐阅读