🍵

React Native, react-navigation 画面遷移で再描画されない時の修正

2021/11/22に公開

概要:

react-navigationで、画面遷移後に再描画されない時の修正になります。

  • createStackNavigatorを使う。

  • 複数画面構成で、screeen1/一覧 ⇒ screen2/追加 ⇒ もどる/screeen1

の順番で、クラウドDBに追加したデータが反映されない場合。

  • 元画面/screeen1 フォーカスが移動した時に、再描画処理を追加しないと、データが反映できない。
    ようでしたので、調査しました。

構成

  • @react-navigation/native: 6.0.6
  • React Native: 0.64.3
  • @apollo/client: 3.4.17

関連

https://qiita.com/sobameshi0901/items/6207a7c3d23d879c51b8


  • 修正: src/MainScreen.tsx

  • componentDidMountに、

this.focusListerner = this.props.navigation.addListener("focus"

追加し、focusイベントが発火されるらしいので。コールバックで再描画を実行する

MainScreen.tsx
export class MainScreen extends React.Component<IProps, IState>{
  focusListerner = null
  constructor(props: any) {
    super(props)
    this.state = {
      items: []
    };
  }
  async componentDidMount(){
    console.log("#componentDidMount");
    try{
      await this.getTasks();
      this.focusListerner = this.props.navigation.addListener("focus", async () => {
        await this.getTasks();
      });
    } catch (e) {
      console.error(e);
    }
  }
  componentWillUnmount() {
    try{
      this.focusListerner.remove();
    } catch (e) {
      console.error(e);
    }    
  }


  • 戻る画面は、backボタンや、navigation.goBack()

の通常の画面遷移で、問題なく。再描画できるように。なりました

....

Discussion