Skip to content

2024年10月随笔

nvm安装新的node版本报错

以前的淘宝镜像已经不再使用,现在需要使用新的淘宝镜像

修改: 找到\nvm\nvm\settings.txt文件,配置如下

bash
node_mirror: https://npmmirror.com/mirrors/node/

npm_mirror: https://npmmirror.com/mirrors/npm/

全局配置最新淘宝镜像

bash
1、npm cache clean --force 清空缓存

2、npm config set registry https://registry.npmmirror.com // 设置最新的镜像源(淘宝)

3、npm config get registry // 查看源

React中动态加载外部Js

jsx
import React, { useEffect } from 'react';

function App() {
  useEffect(() => {
    const script = document.createElement('script');
    script.src = 'https://xxxxxxxx.js';
    script.async = true;

    script.onload = () => {
      console.log('External script loaded');
    };

    document.head.appendChild(script);

    // 清理函数
    return () => {
      document.head.removeChild(script);
    };
  }, []);

  return null
}

export default App;

React中暴露子组件方法

使用 forwardRefuseImperativeHandle

jsx
import React, { useRef, forwardRef, useImperativeHandle } from 'react';

// 子组件
const ChildComponent = forwardRef((props, ref) => {
  // 定义要暴露的方法
  const showAlert = () => {
    alert('Hello from ChildComponent!');
  };

  // 使用 useImperativeHandle 暴露方法
  useImperativeHandle(ref, () => ({
    showAlert,
  }));

  return <div>Child Component</div>;
});

// 父组件
const ParentComponent = () => {
  // 创建 ref
  const childRef = useRef(null);

  // 调用子组件的方法
  const callChildMethod = () => {
    if (childRef.current) {
      childRef.current.showAlert();
    }
  };

  return (
    <div>
      <ChildComponent ref={childRef} />
      <button onClick={callChildMethod}>Call Child Method</button>
    </div>
  );
};

export default ParentComponent;

useImperativeHandle这个 Hook 用于自定义暴露给父组件的属性和方法。它接收两个参数:ref 和一个返回对象的函数

pnpm清除缓存

bash
pnpm store prune

这个命令会清理不再被任何项目使用的包,并优化存储空间。

bash
rm -rf ~/.pnpm-store/v3

如果你需要更彻底地清除所有缓存,可以使用以下命令:

上次更新于: