LoginSignup
0
0

More than 1 year has passed since last update.

propsの更新が反映されない問題に直面した話

Posted at

はじめに

私はしばらく前からReactが気になっていて、この間ついに手を出しました。
まずは簡単なWebアプリを作ってみようと思い、コードを書いて動作確認していたのですが、嵌った点があるので書いていきます。

やっていたこと

まず、アプリ全体のコンポーネントを作成しました。

App.tsx
import {React} from 'react';
import ComponentA from './componentA.tsx';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      fuga: /* Object */
    };
  }

  onEvent(e) {
    this.setState(
      () => {
        {fuga: /* new Object */}
      }
    );
  }

  render() {
    return (
      <div
        onClick={this.onEvent.bind(this)}
      >
        <ComponentA
          fuga={this.state.fuga}
        />
      </div>
    );
  }
}

export default App;

後で書くコンポーネントに、propとしてfugaというオブジェクトを渡すというものになっています。

ダメだった例

内部のコンポーネントのコードを、まず下記のようにしました。

componentA.tsx
import {React} from 'react';

class ComponentA extends React.Component {
  constructor(props) {
    super(props);
    this.state = {hoge: this.fuga(this.props.piyo)}
  }

  fuga(piyo) {
    // 値の加工処理
  }

  render() {
    return (<div>{this.state.hoge}</div>);
  }
}

export default ComponentA;

そして実際にアプリを起動して動作確認をしたのですが、画面をクリックしても何も反応がありませんでした。
どこで問題が起こっているかを探ってみたところ、どうもApp内のthis.state.fugaの更新はされているものの、ComponentAthis.state.hogeが更新されず、従ってComponentAの更新もされていないようでした。

成功した例

色々方法を考え試した結果、以下のコードになりました。

componentA.tsx
import {React} from 'react';

class ComponentA extends React.Component {
  constructor(props) {
    super(props);
  }

  fuga(piyo) {
    // 値の加工処理
  }

  render() {
    return(<div>{this.fuga(this.props.piyo)}</div>)
  }
}

export default ComponentA;

constructor内でthis.statethis.propsを用いて定義せず、render関数内にthis.propsを用いた処理を書くということで解決できるようでした。

おわりに

Reactは奥が深いですね…。

この問題について上手く説明できる方がいらっしゃいましたら、コメント等頂けると有り難いです。

0
0
2

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
0
0