react中setState用法


setState()更新狀態的2種寫法
  1. setState(updater, [callback]), updater為返回stateChange對象的函數: (state, props) => stateChange 接收的state和props被保證為最新的
  2. setState(stateChange, [callback]) stateChange為對象, callback是可選的回調函數, 在狀態更新且界面更新后才執行
  3. 總結: 對象方式是函數方式的簡寫方式 如果新狀態不依賴於原狀態 ===> 使用對象方式 如果新狀態依賴於原狀態 ===> 使用函數方式 如果需要在setState()后獲取最新的狀態數據, 在第二個callback函數中讀取
setState()更新狀態是異步還是同步的?
  1. 執行setState()的位置? 在react控制的回調函數中: 生命周期勾子 / react事件監聽回調 非react控制的異步回調函數中: 定時器回調 / 原生事件監聽回調 / promise回調
  2. 異步 OR 同步? react相關回調中: 異步 其它異步回調中: 同步
關於異步的setState()
  1. 多次調用, 如何處理? setState({}): 合並更新一次狀態, 只調用一次render()更新界面 ---狀態更新和界面更新都合並了 setState(fn): 更新多次狀態, 但只調用一次render()更新界面 ---狀態更新沒有合並, 但界面更新合並了
  2. 如何得到異步更新后的狀態數據? 在setState()的callback回調函數中
面試題
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>03_setState()面試題</title>
</head>
<body>

<div id="example"></div>

<script type="text/javascript" src="./js/react.development.js"></script>
<script type="text/javascript" src="./js/react-dom.development.js"></script>
<script type="text/javascript" src="./js/babel.min.js"></script>

<script type="text/babel">
class StateTest extends React.Component {

state = {
  count: 0,
}

componentDidMount() {
  this.setState({count: this.state.count + 1})
  this.setState({count: this.state.count + 1})
  console.log(this.state.count) // 2 ==&gt; 0

  this.setState(state =&gt; ({count: state.count + 1}))
  this.setState(state =&gt; ({count: state.count + 1}))
  console.log(this.state.count) // 3 ==&gt; 0

  setTimeout(() =&gt; {
    this.setState({count: this.state.count + 1})
    console.log(&#39;timeout&#39;, this.state.count) // 10 ==&gt; 6

    this.setState({count: this.state.count + 1})
    console.log(&#39;timeout&#39;, this.state.count) // 12 ==&gt; 7
  }, 0)

  Promise.resolve().then(value =&gt; {
    this.setState({count: this.state.count + 1})
    console.log(&#39;promise&#39;, this.state.count)  // 6 ==&gt;4

    this.setState({count: this.state.count + 1})
    console.log(&#39;promise&#39;, this.state.count) // 8 ==&gt; 5
  })
}

render() {
  const count = this.state.count
  console.log(&#39;render&#39;, count)  // 1 ==&gt; 0   4 ==&gt;3   5 ==&gt;4  7 ==&gt;5  9 ==&gt;6  11 ==&gt;7
  return (
    &lt;div&gt;
      &lt;p&gt;{count}&lt;/p&gt;
    &lt;/div&gt;
  )
}

}

ReactDOM.render(<StateTest/>, document.getElementById('example'))

</script>
</body>
</html>

 


免責聲明!

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



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