【react-native】componentDidmountでrender直後にbooleanをsetStateしてはいけない

今回は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としておけば

今回の地雷を回避できます。

>株式会社シーポイントラボ

株式会社シーポイントラボ

TEL:053-543-9889
営業時間:9:00~18:00(月〜金)
住所:〒432-8003
   静岡県浜松市中央区和地山3-1-7
   浜松イノベーションキューブ 315
※ご来社の際はインターホンで「316」をお呼びください

CTR IMG