1、箭头函数
import React, {useState} from "react";
const App1 = () => {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={event => setCount(count + 1)}>count:{count}</button>
</div>
)
}
export default App1;
2、useState
import React, {useEffect, useRef, useState} from "react";
const App2 = () => {
const [count, addCount] = useState(0);
return (
<div>
<button onClick={event => addCount(count + 1)}>count1:{count}</button>
</div>
)
}
export default App2;
3、useEffect
import React, {useEffect, useState} from "react";
function useCount(initVlue) {
const [count, setCount] = useState(initVlue);
return [count, () => {
setCount(count + 1)
}]
}
function log(count) {
console.log('你已经点击:' + count + '下了')
}
function useInterval(callback, time) {
useEffect(() => {
const i = setInterval(callback, time);
return () => {
clearInterval(i)
}
}, [])
}
const App3 = () => {
const [count1, addCount1] = useCount(0);
const [count2, addCount2] = useCount(0);
const [count3, setCount3] = useState(0);
useInterval(() => {
setCount3(prevState => prevState + 1)
//这个方式只能第一次生效,后面不生效,上面得函数是可以得
//setCount3(count3 + 1)
}, 1000);
//表示起了什么作用,这块表示骑了打印日志的作用,理解成一个描述,而不是一个方法调用
//useEffect(log.bind(count1,[1])); 依赖1次执行的结果,只执行一次
//useEffect(log.bind(count1),[]); 依赖空执行的结果,只执行一次
useEffect(log.bind(null, count1)); //依赖count1执行的结果,每次都执行
return (
<div>
<button onClick={event => addCount1()}>count1:{count1}</button>
<button onClick={event => addCount2()}>count2:{count2}</button>
<button onClick={event => setCount3(count3 + 1)}>count3:{count3}</button>
</div>
)
}
export default App3;
4、useReducer
import React, {useReducer} from "react";
function reducer(state, action) {
switch (action.type) {
case 'add':
return state + 1;
case 'red':
return state - 1;
default :
throw 'erro'
}
}
const App4 = () => {
const [number, dispatcher] = useReducer(reducer, 0)
return (
<div>
<p>your number is {number}</p>
<button onClick={event => dispatcher({type: 'add'})}> +</button>
<button onClick={event => dispatcher({type: 'red'})}> -</button>
</div>
)
}
export default App4;