React 常用Hooks (二)

useReducer

总的来说useReducer是useState的复杂版和redux差不多

import React, { useState, useReducer, createContext, useContext, useEffect, useMemo, useRef } from 'react';



const initial = {
  n: 0
};
//创建初始值

const reducer = (state: any, action: any) => {
  //创建所有操作reducer(state,action)

  if (action.type === "add") {
    return { n: state.n + action.number };
  } else if (action.type === "multi") {
    return { n: state.n - action.number };
  } else {
    throw new Error("unknown type");
  }
};


function App() {
  const [state, dispatch] = useReducer(reducer, initial);
  const { n } = state;
  const onClick = () => {
    dispatch({ type: "add", number: 1 });
    // 传给reducer()进行操作修改值
  };
  const onClick2 = () => {
    dispatch({ type: "multi", number: 2 });
  };
  return (
    <div className="App">
      <h1>n: {n}</h1>

      <button onClick={onClick}>+1</button>
      <button onClick={onClick2}>+2</button>
    </div>
  );
}



export default App;


除了没有使用到高阶组件外都是差不多的,后面会说到如何用useReducer + Context替代Redux

useRef

如果你需要一个值在组件不断render时 保持不变 ,那么你就会用到 useRef()

因为useRef()创建了一个普通的JavaScript对象。useRef()与{current: …}自己创建对象之间的唯一区别是,useRef它将在每个渲染器上为您提供相同的ref对象。
请记住,内容更改时useRef 不会通知您。对该.current属性进行突变不会导致重新渲染

import React, { useState, useReducer, createContext, useContext, useEffect, useMemo, useRef } from 'react';
import { render } from '@testing-library/react';




function App() {
  console.log("app执行了")
  const count = useRef(0)//在没一次渲染的时候都不会重新 变化 都是同一个
  const [n, setN] = useState(0)
  const onclick = () => {
    setN(n + 9)
  }
  useEffect(() => {
    count.current += 1
    console.log(count.current)
  })
  return (
    <div className="sss">

      <button onClick={onclick}>我是N</button>
    </div>

  );
}



export default App;

/**
 *
 * 如果你需要一个值在组件不断render时 保持不变 useRef(0)
 * 初始化 const count =useRef(0)
 * 读取:count.current
 *
 * 为什么需要current?
 * 为了保证两次useRef 是同一个值
 * 他不会刷新UI
 *
 */

详细请参见 官网介绍

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值