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

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

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:

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

And I have a functional component called File.js:

import React, { useEffect } from "react";
import { a } from "./test";

let data = "hello";

function File() {
    useEffect(() => { a(data) }, [])
    return (<div>something</div>)
}

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

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

and i have a functional component called File.js

import React, {useEffect} from &quot;react&quot;;
import {a} from &quot;./test&quot;;

let data = &quot;hello&quot;

function File() {
useEffect(()=&gt; {a(data)},[]}
  return ( &lt;div&gt;something&lt;/div&gt;)
}

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

import React, { useEffect } from 'react';
import { a } from './test';

let data = 'hello';

function File() {
  useEffect(() => a(data), []);
  return <div>something</div>;
}

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

import React, { useEffect } from &#39;react&#39;;
import { a } from &#39;./test&#39;;

let data = &#39;hello&#39;;

function File() {
  useEffect(() =&gt; a(data), []);
  return &lt;div&gt;something&lt;/div&gt;;
}

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:

确定