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。
相关推荐
于慨10 小时前
tauri
java·服务器·前端
贼爱学习的小黄11 小时前
NC BIP参照开发
java·前端·nc
小江的记录本11 小时前
【MyBatis-Plus】MyBatis-Plus的核心特性、条件构造器、分页插件、乐观锁插件
java·前端·spring boot·后端·sql·tomcat·mybatis
光影少年11 小时前
如何进行前端性能优化?
前端·性能优化
Dxy123931021611 小时前
js如何把字符串转数字
开发语言·前端·javascript
爱写bug的野原新之助11 小时前
爬虫之补环境:加载原型链
前端·javascript·爬虫
陈广亮11 小时前
工具指南7-Unix时间戳转换工具
前端
NGBQ1213811 小时前
Adobe-Premiere-Pro-2026-26.0.2.2-m0nkrus 全解析:专业视频编辑软件深度指南
前端·adobe·音视频
北城笑笑11 小时前
Chrome:Paused in debugger 的踩坑实录:问题排查全过程与终极解决方案( 在调试器中暂停 )
前端·chrome
haorooms11 小时前
Promise.try () 完全指南
前端·javascript