Is there a proper way to use useNavigation() hook

2019-08-24 02:58发布

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条回答
萌系小妹纸
2楼-- · 2019-08-24 03:51

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 to be called by it's "user" 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");
}, []);
查看更多
登录 后发表回答