浜松のWEBシステム開発・スマートフォンアプリ開発・RTK-GNSS関連の開発はお任せください
株式会社シーポイントラボ
TEL:053-543-9889
営業時間:9:00~18:00(月〜金)
住所:静岡県浜松市中区富塚町1933-1 佐鳴湖パークタウンサウス2F

【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としておけば

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

  • この記事いいね! (0)