【问题标题】:unable to update object using hooks in react无法在反应中使用钩子更新对象
【发布时间】:2023-01-22 09:06:14
【问题描述】:

我有一个函数可以使用 useState 挂钩根据应用程序名称更新我的对象值。但是我无法使用挂钩,它给出了无效挂钩调用的错误。

实现相同目的的任何其他方法也将起作用。

var myfun = (function() {

  const APP_NAME= "sample app"
  const [object, setObject] = useState({obj: 'value'})

  if(APP_NAME =="sample app") {
        setObject({obj:'new value'})
         console.log('here')
     }
      return object
});

myfun(); 

【问题讨论】:

  • 这个函数在哪里调用(应该在组件内)? + 'return obj' 可能会失败,因为 obj 没有定义。
  • 你能分享你得到的完整错误吗?
  • 你为什么在函数中使用 useState 。如果您使用的是功能组件,它总是返回 jsx 或 null。
  • @JiaSH 我已经更新了代码,我正在尝试从返回语句中获取更新的对象。
  • 为什么应用程序名称会更改?

标签: javascript reactjs react-native


【解决方案1】:

创建一个自定义 Hook 而不是该函数:

const useMyFun = () => {
    const [object, setObject] = useState({obj: 'value'});

    const APP_NAME = 'sample name';

    useEffect(() => {
        if (APP_NAME === 'sample name') setObject({obj: APP_NAME});
    }, [APP_NAME]);

    return object;
}


// In the component you need it:

const SomeComponent = () => {

    // will update if state changes in the useMyFun Hook;
    const appname = useMyFun();


    // rest of your component code
    ...
}

确保使用功能组件来使用它。

注意:但这只有在 APP_NAME 发生变化时才有用。 否则你可以只使用一个简单的三元运算符:

   const object = APP_NAME === 'sample name' ? {obj: APP_NAME} : {obj: 'value'}

【讨论】:

  • 我必须在同一个文件中调用该函数,当我调用它时,我遇到了无效挂钩调用错误。钩子只能在函数组件的内部调用。
  • 好吧,错误是明确的:'​​Hooks can only be called inside of a function component.'你不能在组件生命周期之外使用 hooks ^^
【解决方案2】:

尝试像这样将挂钩调用移到函数之外,我认为无效的挂钩调用错误将消失:

import React from "react";
import { useState } from "react";

function App() {
  const [object, setObject] = useState({ obj: "value" });

  const myfun = () => {
    const APP_NAME = "sample app";
    if (APP_NAME === "sample app") {
      setObject({ obj: "new value" });
      console.log("here");
    }
    return object;
  };

  myfun();

  return (
    ....
  );
}

export default App;

我希望这可以帮助你 。

【讨论】:

    【解决方案3】:

    如果以上所有答案都不起作用,请寻找无限反应钩子循环(通常使用 useEffect);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      • 2020-10-02
      • 2021-11-09
      相关资源
      最近更新 更多