質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
JavaScript

JavaScriptは、プログラミング言語のひとつです。ネットスケープコミュニケーションズで開発されました。 開発当初はLiveScriptと呼ばれていましたが、業務提携していたサン・マイクロシステムズが開発したJavaが脚光を浴びていたことから、JavaScriptと改名されました。 動きのあるWebページを作ることを目的に開発されたもので、主要なWebブラウザのほとんどに搭載されています。

React.js

Reactは、アプリケーションのインターフェースを構築するためのオープンソースJavaScriptライブラリです。

Q&A

解決済

1回答

5527閲覧

react 配列をstateに入れる

cheche0830

総合スコア187

JavaScript

JavaScriptは、プログラミング言語のひとつです。ネットスケープコミュニケーションズで開発されました。 開発当初はLiveScriptと呼ばれていましたが、業務提携していたサン・マイクロシステムズが開発したJavaが脚光を浴びていたことから、JavaScriptと改名されました。 動きのあるWebページを作ることを目的に開発されたもので、主要なWebブラウザのほとんどに搭載されています。

React.js

Reactは、アプリケーションのインターフェースを構築するためのオープンソースJavaScriptライブラリです。

0グッド

0クリップ

投稿2018/07/05 03:18

constructor(props) { super(props); this.state = { count:null }; } componentDidMount = () => { let list = []; for(let i = 0; i < 3; i++) { list.push("hoge"); } console.log(list);//(3)["hoge","hoge","hoge"] this.setState({ count: list }); console.log(this.state.count);//null }

上記の感じで、配列をstate.countに入れたいのですが、
nullのままになってしまいます。
どのようにするのが正しいのでしょうか?

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

jun68ykt

2018/07/05 03:26

count の変化を見るための、console.log(this.state.count); を、 render() { console.log(this.state.count); ・・・ のように、 render 本体の最初に移動してみると、いかがでしょうか?
cheche0830

2018/07/05 03:54

ありがとうございます!そちらでもみることができました!stateの更新はできていたみたいなのですが、logを見るタイミングが早かったようでした!
guest

回答1

0

ベストアンサー

コード

import React, { Component } from "react"; import ReactDOM from "react-dom"; class App extends Component { constructor(props) { super(props); this.state = { items: null } } componentDidMount() { const newItems = ['a', 'b', 'c']; this.setState({ items: newItems }, () => { console.log('callback', this.state.items); // ["a", "b", "c"] }) console.log('まだnullのまま', this.state.items) // null } componentWillUpdate(nextProps, nextState) { console.log('componentWillUpdate', nextState.items); // ["a", "b", "c"] } render() { return ( <h1>Hello World</h1> ) } } ReactDOM.render( <App />, document.getElementById("root") );

Demo => https://codesandbox.io/s/qvzjm1q91q

解説

上記の感じで、配列をstate.countに入れたいのですが、nullのままになってしまいます。

結論から言いますと、正しくstateの更新自体は出来ています。単に、console.logを差し込むタイミングが後述の理由により、不適切であるため、nullとなってしまうだけの話です。

this.setState({ count: list }); console.log(this.state.count);//null

this.setStateメソッドは非同期実行されるため、上記のようにthis.setStateメソッドの実行直後に、console.logで変更後のstateを確認しようとしても、その段階ではまだ、stateの更新が実行すらされていません。そのため、結果はnullとなります。

単にthis.setStateによってstateが変更されているかをログ出力して確認したいだけであれば、this.setStateメソッドは第2引数にstateの変更が完了した後に呼ばれるコールバック関数を渡すことが出来るので、そちらのほうでログ出力してあげると良いかと思います。

もしくは、stateupdateされた後に呼ばれるライフサイクルメソッド「componentWillUpdate」内で、変更後のstateを確認しても良いかもしれません。

参考

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

https://reactjs.org/docs/react-component.html#setstate

補足

componentDidUpdate(prevProps, prevState, snapshot)

https://reactjs.org/docs/react-component.html#componentdidupdate

回答に載せたコードではcomponentWillUpdateメソッドを使ってますが、React16.3以降ではcomponentWillUpdateの利用を新規開発で利用するのは非推薦になっているので、代わりにcomponentDidUpdatestateの変更を確認するのが適切と言えます。(上の引用文の中でもsetStateメソッドのコールバックか、componentDidMountメソッド内で、、、と記載もありますね。)

投稿2018/07/05 03:31

編集2018/07/05 03:57
HayatoKamono

総合スコア2415

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

cheche0830

2018/07/05 03:53

なるほどですね!reactはタイミングがなかなか難しいですね・・・ setStateにコールバック関数を付けれるのは知らなかったです! ありがとうございました!
og24715

2018/07/05 04:31

state が更新されると render() が必ず走るので(厳密には間違い)その中で console.log(this.state) はよく確認でやりますね。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問