Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

reactjs - Export function from inside a React function

I have a function that handles React Native location. For demonstration:

const useLocation = () => {
  const [fetchingLocation, setFetchingLocation] = useState(true);
  ...

  const changeSystemPermissions = useCallback(() => {...});

  useEffect(() => {
    //does many things
  }, [...])
}

I need to have the function changeSystemPermissions inside useLocation as it uses the state. I realize that I can export the changeSystemPermissions function as a const with a return [changeSystemPermissions, ...] and then import it in another component with:

const [
  changeSystemPermissions,
  ...
] = useLocation();

However, it will ALSO run the useEffect function. I do want it to run once, but I need to access changeSystemPermissions in several other components and I don't want the useEffect to run multiple times.

I was thinking I will just take out the changeSystemPermissions function outside of useLocation, but it needs to use the state. I suppose I COULD pass the state vars into the changeSystemPermissions when it is outside useLocation, but that would be verbose and ugly.

How can I export changeSystemPermissions and just that function without having to import the whole useLocation function?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When ever you call a hook inside a React functional component, it will create a new state for that hook and not sharing among components. But there is a library which could help you achieve that:

https://github.com/betula/use-between

You could follow example to use this library or maybe just read the code and utilize the approach for your case to share the hook state between components.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...