Is there a proper way to use useNavigation() hook with useEffect() dependencies?

青春壹個敷衍的年華 提交于 2019-12-11 06:03:35

问题


I'm trying to interact with react-navigation using useNavigation() hook in response to a callback I'm registering in useEffect(). The linter is warning me that useEffect() has a missing dependency. If I add the navigation hook as a dependency, the effect continuously runs. I'm trying to avoid this and wondering if there is a correct way other than ignoring the linter error.

Providing no dependency array results in the same behavior where the effect continuously fires.

This may be an underlying issue with how the useNavigation() hook from react-navigation-hooks package works.

function MyComponent() {
    const navigation = useNavigation();

    useEffect(() => {
        navigation.navigate('Home');
    }, []);
}

Results in:

React Hook useEffect has a missing dependency: 'navigation'. Either include it or remove the dependency array.


回答1:


Just an opinionated guess: It's more a question regarding your "architecture".

For example: Wouldn't it make more sense for the custom useNavigation hook to return a function that can be called by the consumer of the hook instead of an object with all it's functionality?

Here is an example:

const useNavigation = () => {
  const [routes, setRoutes] = useState(null)
  ...

  const navigate = (destination: string) => {
    console.log("navigated to ", destination)
  }

  return { navigate, routes }
}

function App() {
  const { navigate } = useNavigation();

  return (
    <div className="App">
      <h1>Parent</h1>
      <button onClick={() => navigate("Home")}>Navigate me!</button>
    </div>
  );
}

Working Codesandbox: https://codesandbox.io/s/usenavigation-95kql


If you nevertheless want to keep this "architecture", you could use a useRef hook like so:

const navigation = useRef(useNavigation());

useEffect(() => {
    navigation.current.navigate("Home");
}, []);


来源:https://stackoverflow.com/questions/56243575/is-there-a-proper-way-to-use-usenavigation-hook-with-useeffect-dependencies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!