首页 > 解决方案 > 在 React Native 中重新获取和重新渲染组件

问题描述

我有一个 react-native 移动项目,我正在使用 fetch API 从服务器获取数据。所以我的问题是当我在我的应用程序中导航其他组件时,我更新了一些值(通过在服务器中获取)并获取新的值,但是当我回到家庭场景时,我看到旧的获取数据,我如何每次更新它回归主场?

这是我的家庭场景:

export default class Inside extends Component {

    componentWillMount (){
            alert(this.props.userid + this.state.userid);
            fetch('http://xxx/fetch_info', {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    check: this.props.userid
                }),
            }).then((response) => response.json())
                .then((responseJson) => {
                    alert(responseJson.money + " " + responseJson.mesage);
                    this.setState({
                        example: ex
                    });

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

constructor(props) {
        super(props);
        this.state = {
            ....
            check: this.props.exp
        };
    }

render(){
 <Text> {this.state.stuff} </Text>
 }
}

我的场景:

<Scene key="main">
    <Scene key="home" component={Home}  initial/>
    <Scene  key ="money" component={Money} />
</Scene>

所以每次我回去我都希望自动获取数据,但我不明白怎么做..?

标签: reactjsreact-nativefetch

解决方案


如果您在项目中使用 react-navigation,当您按照您所说的返回“主屏幕”而不是使用 时,this.props.navigation.navigate('yourScreen'); 您可以使用this.props.navigation.replace('yourScreen'); 这将导致您的页面重新加载。这不是一个好习惯,因为您之前的所有导航(您之前导航的屏幕)都松散了,而是临时修复。


推荐阅读