React hooks函数的使用方法

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;

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值