【问题标题】:Re-fetch & Re-render component in React Native在 React Native 中重新获取和重新渲染组件
【发布时间】:2018-04-30 15:46:20
【问题描述】:

我有一个 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>

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

【问题讨论】:

  • 你有没有考虑或正在使用redux
  • 我是个新手,我对 redux 的了解更少,但也许我可以在我的项目中做更多之后使用它。我猜 Redux 对于新手来说看起来很可怕
  • 别担心。 redux 是一个状态容器,正是你想要的。我怀疑是否有人愿意进一步回答这个问题,因为它太大了。学习愉快redux
  • 好的.. 我把它当作我的问题的建议,谢谢。
  • 我不是 100% 确定,但如果它没有重新获取,则意味着您的组件生命周期被搞砸了。尝试添加 componentWillUnmount() 并在导航期间转到新组件之前查看组件是否被破坏。

标签: reactjs react-native fetch


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-11-18
    • 2021-10-28
    • 2021-01-02
    • 2018-12-16
    • 1970-01-01
    • 2019-02-26
    • 2021-06-19
    • 2018-04-22
    相关资源
    最近更新 更多