繁体   English   中英

React Native-使用react-navigation和react-redux在屏幕之间切换时数据丢失

[英]React Native - data is lost when switching between screens using react-navigation and react-redux

我在我的本机应用程序中使用react-redux和react-navigation。

我有一个名为photolist的组件,该组件从数据库中获取所有照片。 有两个屏幕调用此组件。 userProfile屏幕将true和userId photolist给用户照片的照片列表; feed屏幕将false和null photolist给所有照片的照片列表。

在App.js中,我将“提要”屏幕和“用户”屏幕放在同一堆栈中,以便可以轻松导航。

通过这种方法,我可以在App加载时加载主页,查看所有照片,然后转到用户页面并查看用户的照片。 但是从用户页面上,当我单击“后退”按钮返回主页时,不再加载照片。 请注意,在此操作序列中, photolist组件的componentDidMount()函数恰好被调用了两次; 从userProfile返回主供稿时,不会再次调用它。

为什么会发生这种情况,我该如何解决? 有没有一种方法可以保持导航结构,即单击userProfile的后退按钮会将您带回到主供稿页面,而无需再次重新加载主供稿?

photolist.js:

class PhotoList extends React.Component {
    constructor(props) {
        super(props);
    }

    componentDidMount = () => {
        const { isUser, userId } = this.props;

        // load a single user's photos or all photos
        if (isUser) {
            this.props.loadFeed(userId);
        } else {    
            this.props.loadFeed();
        }
    }

    render(){
        return (
            <View style={{flex:1}}>
                <FlatList
                    data = {(this.props.isUser) ? this.props.userFeed : this.props.mainFeed}
                    keyExtractor = {(item, index) => index.toString()}

                    ...
                />
            </View>
        )
    }
}

const mapStateToProps = state => {
    return {
        mainFeed: state.feed.mainFeed,
        userFeed: state.feed.userFeed
    }
}

const mapDispatchToProps = {
    loadFeed
};

export default connect(mapStateToProps, mapDispatchToProps)(PhotoList);

feed.js:

<PhotoList isUser={false} navigation={this.props.navigation}/>

userProfile.js:

<PhotoList isUser={true} userId={this.state.userId} navigation={this.props.navigation}/>

App.js:

const FeedScreenStack = createStackNavigator({
  FeedStack: { screen: feed },
  UserProfile: { screen: userProfile }
});

在堆栈中导航时,React Navigation不会安装和卸载组件。 相反,组件保持安装状态,并具有自定义的反应导航生命周期事件

在场景中添加<NavigationEvents>组件是修复用例的一种方法:

import { NavigationEvents } from 'react-navigation';

class PhotoList extends React.Component {
  componentDidMount() {
    this.loadFeed();
  }

  loadFeed = () => {
    const { isUser, userId } = this.props;

    // load a single user's photos or all photos
    if (isUser) {
      this.props.loadFeed(userId);
    } else {    
      this.props.loadFeed();
    }
  }

  render() {
    return {
      <View>
        <NavigationEvents
          onDidFocus={this.loadFeed}
        />
      </View>
    }
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM