react Hooks :State Hooks的使用,以及设置回调

react普通class组件

import React, {
    
     Component} from 'react'

export default class App extends Component {
    
    
  state = {
    
    
    count: 0
  }
  render() {
    
    
    const {
    
     count } = this.state
    return (
      <div>
        <button
          type="button"
          onClick={
    
    () => {
    
     this.setState({
    
     count: count + 1 }) }}>
          Click:{
    
    count}
        </button>
      </div>
    )
  }
}

使用react Hooks 的函数式组件

import React, {
    
     useState } from 'react'

function App() {
    
    
  const [count, setCount] = useState(0)
  //useState(),返回值是一个只有两个成员的数组,第一个是count本身,第二个是设置count的方法
  return (
    <div>
      <button
        type="button"
        onClick={
    
    () => setCount(count + 1)}>
        Click:{
    
    count}
      </button>
    </div>
  );

}
export default App

如果需要setCount后直接使用count数据,使用的还是旧的count数据,要想使用最新的count数据,必须配合useEffect这个 hook,在 useEffect 的第二个参数中传count就行了,变相的实现了设置回调的效果

useEffect(() => {
    
    console.log(count)}, [count]) 

[count]作为第二个参数,组件重渲染的时候,React 将对前一次渲染的 [count] 和后一次渲染的 [count] 进行比较,如果发生改变,则执行effect,否则就跳过effect

猜你喜欢

转载自blog.csdn.net/weixin_44745920/article/details/114994088
今日推荐