10
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【React】renderでsetState()すると無限ループになる【React Native】

Last updated at Posted at 2018-08-13

何が起きたか

render()内でsetState()を実行してしまい無限ループ

image.png

Calling setState in render causes infinite loop · Issue #5591 · facebook/react

ありがちなソース

ex) 親Componentから子Componentにmethodとvalueをpropsで渡し、子ComponentのonPressイベントでそのmethodを実行する

BadMain.jsx

_onPress = (value) => {
  this.setState({ count: value })
}

render() {
  return( 
    <SubComponent onPress={_onPress} value={value} />
  );
}

BadSub.jsx

const SubComponent = (props) => {
const { onPress, value } = props

  return (
    <TouchableOpacity onPress={onPress(value)}> 
    ...
    </TouchableOpacity>
  );
}

これをやっちゃうと

<TouchableOpacity onPress={onPress(value)}> 

<TouchableOpacity onPress={setState()}> 

と同義になってしまうので、stateの更新=>render=>stateの更新...と無限ルールにハマってしまいます。

どうするか

render外でsetState()を含むmethodを実行する。

GoodMain.jsx

_onPress = (value) => {
  this.setState({ count: value })
}

render() {
  return( 
    <SubComponent onPress={_onPress} value={value} />
  );
}

GoodSub.jsx

const SubComponent = (props) => {
const { onPress, value } = props
const _onSubPress = () => {
  onPress(value);
}

  return (
    <TouchableOpacity onPress={_onSubPress)}> 
    ...
    </TouchableOpacity>
  );
}
10
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?