首页 > 解决方案 > 类型“IntrinsicAttributes”上不存在属性“历史”

问题描述

我通过传递 createBrowserHistory 道具将反应应用程序包装在路由器中。但是在“IntrinsicAttributes & RouterPops”类型上不存在“属性‘历史’”

这是我的 index.tsx

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import { Router } from "react-router-dom";
import history from "../src/utils/history";

ReactDOM.render(
    <Router history={history}>
    <App />
  </Router>,
  document.getElementById("root")
);

这是我的历史.tsx

import { createBrowserHistory } from "history";

const history = createBrowserHistory();

export default history;

我正在使用 react-router-dom v6.0.2

标签: reactjsreact-router-dombrowser-history

解决方案


我怀疑您可以实现更高级别路由器之一的更多逻辑,并使用自定义历史对象获得您想要的行为。

BrowserRouter实现例如:

export function BrowserRouter({
  basename,
  children,
  window
}: BrowserRouterProps) {
  let historyRef = React.useRef<BrowserHistory>();
  if (historyRef.current == null) {
    historyRef.current = createBrowserHistory({ window });
  }

  let history = historyRef.current;
  let [state, setState] = React.useState({
    action: history.action,
    location: history.location
  });

  React.useLayoutEffect(() => history.listen(setState), [history]);

  return (
    <Router
      basename={basename}
      children={children}
      location={state.location}
      navigationType={state.action}
      navigator={history}
    />
  );
}

创建一个CustomRouter使用自定义history对象并管理状态的:

const CustomRouter = ({ history, ...props }) => {
  const [state, setState] = useState({
    action: history.action,
    location: history.location
  });

  useLayoutEffect(() => history.listen(setState), [history]);

  return (
    <Router
      {...props}
      location={state.location}
      navigationType={state.action}
      navigator={history}
    />
  );
};

编辑 property-history-does-not-exist-on-type-in​​trinsicattributes


推荐阅读