react 監聽props變化


新建 forum.jsx 父組件。

import React from 'react';
import ForumDetail from './forumDetail';

export default class Forum extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      type: 1
    };
  }
  render() {
    return (
      <div>
        <ForumDetail value={this.state.type} />
      </div>
    )
  }
}

新建 forumDetail.jsx 子組件。

import React from 'react';

export default class Forum extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      type: ''
    };
  }
  render() {
    return (
      <div>
        {`父組件傳過來的值${this.state.type}`}
      </div>
    )
  }
  // 獲取父組件傳過來的值,這里還可以監聽父組件傳值變了,然后重新賦值給 state。
  // props 表示父組件傳過來的值, state 表示當前子組件的state。
  static getDerivedStateFromProps(props,state) {

    // 父組件傳過來的 type 和 子組件的 type 不一樣,那么子組件重新賦值。
    // 也可以理解成,父組件傳過來的值變了。
    if (props.type !== state.type) {
      // 這里執行相應的方法
      // console.log(123);
      return {
        type,//把父組件最新的props.type重新賦值到 子組件state.type 
      }
    }
    // 父組件的值沒有變化,這里不做任何操作。
    return null
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM