如何在抽屉导航器3.0中单击项目菜单时重置屏幕



当我单击项目菜单时,我有 React 导航的抽屉导航器,例如:

1:点击项目A(屏幕A(->从组件DidMount获取服务器上的一些数据,将一些数据输入到InputText,...

2:打开抽屉菜单,点击项目B(屏幕

B(,然后再次打开菜单,点击项目A(屏幕A(->一些我之前获取的数据仍然存在并且没有重新加载,甚至我之前输入的一些数据也仍然存在,没有重置

我正在使用反应导航 3.1

import { StackActions, NavigationActions, DrawerItems } from 'react-navigation'
<ScrollView>
         <DrawerItems {...this.props}
                      onItemPress={({route, focused}) => {
                        console.log(route)
                        // this.resetStack(route, focused)
                        this.props.onItemPress({ route, focused })
                        //i try to reset at there but nothing
                      }}
         />

所以有人知道如何解决这个问题吗?谢谢

更新:我找到了解决方案。

只需使用:

resetStack = (name, focused) => {
    const resetAction = StackActions.reset({
      index: 0,
      actions: [NavigationActions.navigate({ routeName: 'MenuBar' })],
    })
    this.props.navigation.dispatch(resetAction)
    this.props.navigation.navigate(NavigationActions.navigate({
      routeName: 'MenuBar',
      action: NavigationActions.navigate({ routeName: name.routeName })
    }))
  }
...
<DrawerItems {...this.props}
                       onItemPress={({route, focused}) => {
                         this.resetStack(route, focused)
                       }}
          />

不是最好的解决方案,但我找不到其他更好的:)

class YourComponent extends React.Component {
    state = {
        yourData: null
    };
    fetchData = () = {
        // get some data
    };
    componentDidMount() {
        // you fetched data here:
        const data = fetchData();
        this.setState({ yourData: data });
    }
    componentWillReceiveProps(nextProps) {
        // check if you need to re-fetch data ... in case of new props:
        if (needToReloadData) {
            const data = fetchData();
            this.setState({ yourData: data });
        }
        if(needToReset) {
            this.setState({ yourData: null });
        }
    }
}

componentDidMount屏幕 A 的事件被调用,一旦您从抽屉中选择它......然后在单击另一个屏幕(如屏幕 B ==>屏幕 A 从屏幕上卸载后......这就是为什么当您重新打开屏幕 A ==> componentDidMount 屏幕 A 的事件再次被调用......

为了解决单击时重新加载数据的问题,您需要在componentWillReceiveProps中包含重置逻辑:

  1. componentDidMount 事件.//将在第一次点击时执行。
  2. componentWillReceiveProps//将在下一次后续点击时执行

最新更新