react中父級props改變,更新子級state的多種方法

子組件:react

class Children extends Component {
  constructor(props) {
     super(props);
     this.state = {
       a: this.props.a,
       b: this.props.b,
       treeData: '',
       targets: '',
     }
    }
  componentDidMount() {
   const { a, b } = this.state
   const data = {a,b}
   fetch('/Url', {
     data
   }).then(res => {
   if (res.code === 0) {
     this.setState({
     treeData: res.a,
     targets: res.b,
  })
  } else {
   message.error(res.errmsg)
  }
  })
  }
 test(item1, item2) {
   const data = { item1, item2 }
   fetch('/Url', {data}).then(res => {
     if (res.code === 0) {
       this.setState({
         treeData: res.a,
         targets: res.b,
       })
     } else {
       message.error(res.errmsg)
     }
   })
 }
} export
default Children

方法一:巧用keyreact-router

<Children key={this.state.key} a={this.state.a} b={this.state.b} /> //父組件調用子組件

這種方法是經過key變化子組件會從新實例化 (react的key變化會銷燬組件在從新實例化組件)app

方法二:利用ref父組件調用子組件函數(不符合react設計規範,但能夠算一個逃生出口嘻嘻~)函數

class father extends Component {
    constructer(props) {
      super(props);
      this.state={
a: '1',
b: '2',
}
this.myRef this.test = this.test.bind(this) } change() {
const { a,b } = this.state console.log(
this.myRef.test(a,b)) // 直接調用實例化後的Children組件對象裏函數 } render() { <Children wrappedComponentRef={(inst) => { this.myRef = inst } } ref={(inst) => { this.myRef = inst } } /> <button onClick={this.test}>點擊</button> } }

注:wrappedComponentRef是react-router v4中用來解決高階組件沒法正確獲取到ref( 非高階組件要去掉哦)fetch

方法三:父級給子級傳數據,子級只負責渲染(最符合react設計觀念)推薦!!this

父組件:spa

class father extends Component {
    constructer(props) {
      super(props);
      this.state={
       a:'1',
       b:'2',
       data:'',
      }
    }
  getcomposedata() {
    const { a, b } = this.state
    const data = { a, b }
    fetch('/Url', {data}).then(res => {
      if (res.code === 0) {
        this.setState({
          data:res.data
        })
      } else {
        message.error(res.errmsg)
      }
    })
  }
render() {
 <Children data={this.state.data}} />  
}
}    

子組件:設計

 componentWillReceiveProps(nextProps) {
    const { data } = this.state
    const newdata = nextProps.data.toString()
    if (data.toString() !== newdata) {
      this.setState({
        data: nextProps.data,
      })
    }
  }
注:react的componentWillReceiveProps週期是存在期用改變的props來判斷更新自身state
相關文章
相關標籤/搜索