1. 什么是react hooks?
React Hooks 它是react16.8版本有的
React Hooks是可以让我们在函数式组件中定义 state , 和使用React中的一些特性
2. React Hooks 有哪些中间件?
useState : 让我们可以在函数式组件中定义状态 和 事件处理程序
useEffect : 让我们可以在函数式组件中使用类似生命周期钩子函数
componentDidMount
componentUpdate
componentWillUnmount
案例:实现点击按钮 增加count的一条数据
在组件中引入useState
import { userState } from 'react'
在App组件内以数组形式定义count数据和setCount方法
const [ count, setCount ] = useState (0)
在button按钮上绑定setCount方法,里面传入参数,注意这里传入参数必须要使用箭头函数
<button onClick = { () => { setCount(count+1)}}>+</button>
使用useEffect类似生命周期函数来监听数据,里面接收一个回调函数作为参数
useEffect(()=>{
console.log('count')
})
完整代码如下:
import React, { useState,useEffect } from 'react';
import './App.css';
function App() {
const [count, setCount] = useState (0)
useEffect(()=>{
console.log('count')
})
return (
<div className="App">
<header className="App-header">
<button onClick = { () => { setCount(count+1)}}>+</button>
<p>count: { count }</p>
</header>
</div>
);
}
export default App;