简体   繁体   中英

`useReducer` failing when used in `react-router` route

Using useReducer is throwing an error which tells me that rules of hooks are broken. Why is that happening? Is there and easy way to fix it?

import * as React from "react";
import { useReducer, Reducer } from "react";
import { render } from "react-dom";
import {
  RouteComponentProps,
  BrowserRouter as Router,
  Route,
  Switch
} from "react-router-dom";
import "./styles.css";

const HelloRoute: React.FunctionComponent<RouteComponentProps> = () => {
  const [state, dispatch] = useReducer(state => state, {});
  return <div>Hello Route</div>;
};
function App() {
  return (
    <div className="App">
      <Router>
        <Switch>
          <Route path="/" render={HelloRoute} />
        </Switch>
      </Router>
    </div>
  );
}

const rootElement = document.getElementById("root");
render(<App />, rootElement);

Working sandbox

Issue was in this line

<Route path="/" render={HelloRoute} />

render accepts a function not a component. Do to fix this had to wrap it in arrow function:

<Route path="/" render={(props) => <HelloRoute {...props}/>} />

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