焦点屏幕更改时更新组件

Update Component when Focused screen changes

我在 BottomTabNavigator(React Navigation V5)新闻屏幕和保存屏幕中有两个选项卡。当我在其中一个新闻中单击书签时,它将更新到异步存储并使用 this.props.navigation.navigate("saved") 我移至保存的屏幕

问题是将屏幕导航至保存后我没有看到任何更改。我需要更新组件。使用 getMyObject() 的值,我需要在每次保存的屏幕聚焦时调用下面的函数并更新组件。完整代码 - https://snack.expo.io/@belgin/news-app

   getMyObject = async () => {
    try {
      const jsonValue = await AsyncStorage.getItem('BookMarks');
      if (jsonValue) {
        const data = JSON.parse(jsonValue);
        this.setState({ BookMark_Item : data })
      }
    } catch (e) {
    // read error
    }
};

完整代码https://snack.expo.io/@belgin/news-app

感谢帮助

    import { useIsFocused } from '@react-navigation/native';

function Profile() {
  // This hook returns `true` if the screen is focused, `false` otherwise
  const isFocused = useIsFocused();

  return <Text>{isFocused ? 'focused' : 'unfocused'}</Text>;
}

你可以在useEffect()中调用thin

=====已更新====

 componentDidMount() {
    this.props.navigation.addListener('focus', this._onFocus);
    this.props.navigation.addListener('blur', this._onBlur);
  }

  componentWillUnmount() {
    this.props.navigation.removeListener('blur', this._onBlur);
    this.props.navigation.removeListener('focus', this._onFocus);
  }


  _onFocus = () => {
    console.log("=====_onFocus")
      this.getMyObject()
    // Update focus state. Latter state update is to refresh the content once
    // focus state is updated. Temp fix for react navigation tab swiping issues.
    // See https://github.com/react-community/react-navigation/issues/1257
    this.setState({isFocused: true}, () => { this.setState(this.state)});
  };

  _onBlur = () => {
    this.setState({isFocused: false});
        console.log("=====_onBlur")

  };

这可能有帮助:Link

我找到答案了!您可以只使用此代码,它会启动侦听器以检查它是否已聚焦

  componentDidMount(){
    this.props.navigation.addListener('focus', () => {
      this.getMyObject()
    });
  }

顺便说一句,您必须删除在构造函数中调用的 (this.getMyObject()),因为您使用了 componentDidMount。

constructor(props){
    super(props);
    this.state={
      isLoading : false,
      BookMark_Item:[],
      value:0
    }
    this.getMyObject() // <= remove this
  }

SOLUTION: add below to your code:

componentDidMount() {
    const {navigation} = this.props

    this._unsubscribe = navigation.addListener('focus', () => {
      this.getMyObject()
    });
  }

  componentWillUnmount() {
    this._unsubscribe();
  }

更多:https://reactnavigation.org/docs/navigation-events/#navigationaddlistener