简体   繁体   中英

How to use a hook in React?

I have information in the state ( true or false ) that I want to display if is true this Navbar component, but when I use the hook, I get an error message: hook error

My code:

import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'connected-react-router';

import store, { history } from './reduxStore';
import AppRouterContainer from './pages/AppRouterContainer';

import Feedback from './pages/feedback/Feedback';
import Navbar from './components/Navbar/Navbar';
import { useTypedSelector } from '../src/hooks/useTypedSelector';

const isAuth = useTypedSelector((state) => state.auth.isAuth);

const App = () => (
  <BrowserRouter>
    <Provider store={store}>
      <ConnectedRouter history={history}>
        <AppRouterContainer />
        {isAuth && (
          <Navbar />
        )}
        <Feedback />
      </ConnectedRouter>
    </Provider>
  </BrowserRouter>
);

export default App;
  1. You need to create a wrapper component to have access to store in your context (I think your useTypedSelector() hook needs that access).
  2. You can use hooks only inside a function, not just inside a module.

Check out this example:

import React from 'react';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import { ConnectedRouter } from 'connected-react-router';

import { useTypedSelector } from '../src/hooks/useTypedSelector';
import Navbar from './components/Navbar/Navbar';
import AppRouterContainer from './pages/AppRouterContainer';
import Feedback from './pages/feedback/Feedback';
import store, { history } from './reduxStore';

const NavbarWrapper = () => {
  const isAuth = useTypedSelector((state) => state.auth.isAuth);

  if (!isAuth) {
    return null;
  }

  return <Navbar />;
};

const App = () => (
  <BrowserRouter>
    <Provider store={store}>
      <ConnectedRouter history={history}>
        <AppRouterContainer />
        <NavbarWrapper />
        <Feedback />
      </ConnectedRouter>
    </Provider>
  </BrowserRouter>
);

export default App;

Also, I think you should move the NavbarWrapper component to a separate file.

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