简体   繁体   中英

How to get return data from another file outside of a react component?

I am trying to get react to return data from a non-component file to a component, I am wondering if that is even possible. If you don't get what I mean here is some code:

foo.js:

import random from "./script/stuff/myfantasticfile.js";

export const myFantasticFunction = () =>{
return "Hello world!";
}

App.jsx:

import react from "react";
import Stuff from "./stuff.jsx"
import {myFantasticFunction} from "./foo.js"

function App(){
const myVariable = myFantasticFunction();
return(
<div>
<Stuff/>
<p>{myVariable}</p>
</div>
)

In other words When the code is executed the p tag will say "undefined" and cannot print "Hello world" on the screen.

I have tried to search on google, stackoverflow and some other online coding websites ie: grepper.

If anyone have any idea please share it to me by posting an answer.

kind regards Alvin.

也许你的函数在渲染组件时没有加载,我建议尝试一下:

<p>{myVariable ? myVariable : '' }</p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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