Cannot update a component ナビゲーションコンポーネント の対応

Published: 2023/6/17


問題

ReactNative (expo) で開発をしていて、 ReactNavigation を用いていた。 そこで、以下のようなエラーが発生した。

Warning: Cannot update a component (`Navigatorコンポーネント`) wh
ile rendering a different component (`Screenコンポーネント`). To locat
e the bad setState() call inside `Screenコンポーネント`, follow the st
ack trace as described in https://reactjs.org/link/setstate-in-rende
r

原因と対策

Screen 側のコンポーネントの中で、 setOptions を直に呼んでいたのが原因だった。

https://reactnavigation.org/docs/navigation-prop/

にある通り、

setParams/setOptions etc. should only be called in useEffect/useLayoutEffect/componentDidMount/componentDidUpdate etc. Not during render or in constructor.

であって、コンポーネントの中で直で呼ぶべきではない。

useEffect の中で設定するようにした結果、この Warning は解消した。


Tags: reactreact-navigationreact-native

関連記事