1. 程式人生 > >react中父級props改變,更新子級state的多種方法

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

new 渲染 改變 推薦!! item data class else clas

子組件:

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

方法一:巧用key

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

這種方法是通過key變化對子組件不斷實例化,react的key變化會銷毀組件在重新實例化組件

方法二:利用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

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

父組件:

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

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