首頁  >  文章  >  web前端  >  react更新state方式有哪些

react更新state方式有哪些

藏色散人
藏色散人原創
2022-11-09 15:31:031877瀏覽

react更新state方法有:1、透過key變化子元件,程式碼如「c9b7e0ce16bfd966eb69f18545bf1a19」;2、利用ref父元件呼叫子元件函數;3、透過父級給子級傳數據,子級只負責渲染。

react更新state方式有哪些

本教學操作環境:Windows7系統、react17.0.1版、Dell G3電腦。

react更新state方法有哪些?

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

子元件:

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: &#39;1&#39;,
       b: &#39;2&#39;,
      }
      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:&#39;1&#39;,
       b:&#39;2&#39;,
       data:&#39;&#39;,
      }
    }
  getcomposedata() {
    const { a, b } = this.state
    const data = { a, b }
    fetch(&#39;/Url&#39;, {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影片教學

以上是react更新state方式有哪些的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn