2023-09-27
今回はreact-native-router-fluxを使ったreact画面遷移とreact-nativeのライフサイクルに関わる話です。
react-nativeのライフサイクルも、reactと同じく遷移した後にcomponentDidmountから入るのですが、
このcomponentDidmount辺りでミスを犯しました。
Warning: Can’t call setState (or forceUpdate) on an unmounted component.
This is a no-op, but it indicates a memory leak in your application.
To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
原因:遷移後にすぐcomponentDidmout内でbooleanのstateを変更したのがいけなかったみたい。
js&JSX
</pre> this.state = { isModalVisible: false, } componentDidMount(){ this.setState({ isModalVisible: !this.state.isModalVisible }); } <Modal isVisible={this.state.isModalVisible}> <View style={mainStyle.Modaltyle}> <Text>Modal Content</Text> <GreeButton press={() => {this.start()}} text="はい"/> </View> </Modal> <pre>
最初の段階でコンストラクタの段階でfalseにしておいたのに、render後に行われるcomponentDidmount内で
もう一回isModalVisibleでマウントをしてモーダルを呼び出している。これがマウントの際に何かのタイミングで
バグの要因になってアプリ内に影響を及ぼすことが危惧されてエラーが起きたのだと思われます。
遷移先のcomponentDidmountで二度処理を避ける・コンストラクタの段階でisModalVisible: trueとしておけば
今回の地雷を回避できます。