getting value undefined into function, the function is declare into another js file and used inside the component in react

huangapple go评论117阅读模式
英文:

getting value undefined into function, the function is declare into another js file and used inside the component in react

问题

I have one JS file called test.js and I have one function inside it:

  1. export const a = (data) => {
  2. console.log(data);
  3. }

And I have a functional component called File.js:

  1. import React, { useEffect } from "react";
  2. import { a } from "./test";
  3. let data = "hello";
  4. function File() {
  5. useEffect(() => { a(data) }, [])
  6. return (<div>something</div>)
  7. }
  8. export default File;

I get the output in console.log as undefined, but I should get "hello." I don't understand what the problem is. Please help me.

英文:

i have one js file called test.js and i have one function inside it

  1. export const a =(data)=&gt;{
  2. console.log(data)
  3. }

and i have a functional component called File.js

  1. import React, {useEffect} from &quot;react&quot;;
  2. import {a} from &quot;./test&quot;;
  3. let data = &quot;hello&quot;
  4. function File() {
  5. useEffect(()=&gt; {a(data)},[]}
  6. return ( &lt;div&gt;something&lt;/div&gt;)
  7. }
  8. export default File;

and i get output in console.log is undefined, i should get "hello". i dont understand what the problem please help me

答案1

得分: 1

After fixing the useEffect() wrong bracket type issue the code should work just fine:

File.js

  1. import React, { useEffect } from 'react';
  2. import { a } from './test';
  3. let data = 'hello';
  4. function File() {
  5. useEffect(() => a(data), []);
  6. return <div>something</div>;
  7. }
  8. export default File;

Here I've implemented it in a minimal code environment, and it is printing hello as intended.

StackBlitz Virtual Environment Link

英文:

After fixing the useEffect() wrong bracket type issue the code should work just fine:

File.js

  1. import React, { useEffect } from &#39;react&#39;;
  2. import { a } from &#39;./test&#39;;
  3. let data = &#39;hello&#39;;
  4. function File() {
  5. useEffect(() =&gt; a(data), []);
  6. return &lt;div&gt;something&lt;/div&gt;;
  7. }
  8. export default File;

Here I've implemented it in a minimal code environment, and it is printing hello as intended.

StackBlitz Virtual Environment Link

huangapple
  • 本文由 发表于 2023年5月6日 19:28:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76188609.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定