React概念理解

1 useEffect

文章推荐

  1. https://segmentfault.com/a/1190000018639033
  2. https://juejin.cn/post/7044161793471545381
javascript 复制代码
  useEffect(() => {
    console.log('====111111======');
    return () => {
      console.log('=======222222=======');
    };
  });

在每次代码刷新时候都会打印111111和222222
javascript 复制代码
const [state, dispatch] = useReducer(
    (oldState, payload) => {
      if (payload.type === 'tick') {
        return {
          ...oldState,
          count: oldState.count + oldState.step,
        };
      }

      return {
        ...oldState,
      };
    },
    { count: 0, step: 1, type: '' },
  );
  useEffect(() => {
    console.log('========111111======');
    const id = setInterval(() => {
      console.log('========222222======', state.count);
      dispatch({ type: 'tick' }); 
    }, 1000);
    return () => {
      console.log('========333333======', state.count);
      clearInterval(id);
    };
  }, [dispatch]);

 <h1>{state.count}</h1>

console.log('========111111======'); 只会执行一次,****说明每次返回的dispatch都是同一个函数。

console.log('========222222======', state.count);会被多次执行,但是打印出来的state.count会一直是0 (因为Capture Value的原因)

console.log('========333333======', state.count); 不会执行,页面其他state更新它也不受影响
页面其他state更新不会影响到上面useEffect内部执行。

h1标签里面的值会正常一秒增加一次。


可以把上面理解成一个小型的Redux。
相关推荐
二哈喇子!3 小时前
BOM模型
开发语言·前端·javascript·bom
二哈喇子!3 小时前
Vue2 监听器 watcher
前端·javascript·vue.js
摘星编程3 小时前
OpenHarmony + RN:Bluetooth连接蓝牙外设
react native·react.js·harmonyos
yanyu-yaya4 小时前
前端面试题
前端·面试·前端框架
二哈喇子!4 小时前
使用NVM下载Node.js管理多版本
前端·npm·node.js
GGGG寄了4 小时前
HTML——文本标签
开发语言·前端·html
摘星编程5 小时前
在OpenHarmony上用React Native:ActionSheet确认删除
javascript·react native·react.js
2501_944521595 小时前
Flutter for OpenHarmony 微动漫App实战:推荐动漫实现
android·开发语言·前端·javascript·flutter·ecmascript
Amumu121386 小时前
Vue核心(三)
前端·javascript·vue.js
CoCo的编程之路6 小时前
2026 前端效能革命:如何利用智能助手实现“光速”页面构建?深度横评
前端·人工智能·ai编程·comate·智能编程助手·文心快码baiducomate