首页 > 解决方案 > 当钩子在多个地方使用时,自定义钩子中的 useEffect 会冻结我的 react-native 应用程序

问题描述

我创建了一个自定义钩子,它从使用 Async-Storage 的 api 中获取设置。

// Takes the key/name of the setting to retrieve
export const useSettings = (key) => {

  // stores the json string result in the setting variable
  const [setting, setSetting] = useState("");

  const deviceStorage = useContext(DeviceStorageContext);

  useEffect(() => {
    getValue()
     .then(value => setSetting(value));
  }, []);

  // gets value from my custom api that uses Async-Storage to handle r/w of the data.
  const getValue = async () => await deviceStorage.getValueStored(key);
  
  const setValue = async (value) => { 
      await deviceStorage.setValueStored(key, value);
      getValue().then(value => setSetting(value));
  };

  
  const removeValue = async () => { }

  return [setting, { setValue,removeValue }];
};

这在 Main.jsx 中按预期工作,没有任何问题。

const Main = () => {
  const [units, operations] = useSettings('units');

  useEffect(() => {
    const initSettings = async () => {
      if (units) {
       console.log(units)
       return;
     }
      await operations.setValue({ pcs: 1, box: 20 });
    };
    initSettings();
  }, []);

但是,当我什至只是在 Form.jsx 中调用 useSetting 挂钩并访问该页面时,它会将我的整个应用程序冻结到该页面。

const FormView = ({ handleReset, handleSubmit }) => {
  const [setting,] = useSettings('units');

删除 useState 和 useEffect 可以修复它并直接调用这些方法,但我真的不想在整个项目中调用 getValue() 并使用 async/await 代码来处理它。

现在坚持了几个小时。任何帮助将不胜感激。

谢谢你。

标签: reactjsreact-native

解决方案


这是 FormView 中的一个下拉组件库,它搞砸了。删除该库修复了它。


推荐阅读