简体   繁体   English

无法在反应中使用钩子更新 object

[英]unable to update object using hooks in react

I have a function that will update my object value depending on the app name using useState hook.我有一个 function,它将根据使用 useState 挂钩的应用程序名称更新我的 object 值。 But I am not able to use the hook, it gives error invalid hook call.但是我无法使用挂钩,它给出了无效挂钩调用的错误。

Any other way to achieve the same will also work.实现相同目的的任何其他方法也将起作用。

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(); 

Create a custom Hook instead of that Function:创建一个自定义 Hook 而不是 Function:

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
    ...
}

make sure you use functional components to use this.确保使用功能组件来使用它。

NOTE: but this will only be useful if APP_NAME will ever change.注意:但这只有在 APP_NAME 发生变化时才有用。 otherwhise you could just use a simple ternary operator:否则你可以只使用一个简单的三元运算符:

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

Try to move the hook call outside the function like this and the invalid hook call error will disapear i think:尝试像这样将挂钩调用移到 function 之外,我认为无效的挂钩调用错误将消失:

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;

i hope this helps you.我希望这可以帮助你。

If all the above answers don't work look for an infinite react hook loop (usually with useEffect);如果以上所有答案都不起作用,请寻找无限反应钩子循环(通常使用 useEffect);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM