在“反应路由器”路线中使用时,“ useReducer”失败

时间:2019-08-23 07:12:26

标签: javascript reactjs typescript react-router react-hooks

使用useReducer会引发错误,告诉我挂钩规则已损坏。为什么会这样呢?是否有简单的方法来解决它?

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);

工作sandbox

1 个答案:

答案 0 :(得分:0)

问题在这一行

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

render接受功能而不是组件。要解决此问题,必须将其包装在箭头功能中:

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