我创建了以下非常简单的react应用程序来模拟我在生产应用程序中看到的行为。
根组件:
import {
BrowserRouter as Router,
Route,
RouteComponentProps,
Switch,
} from "react-router-dom";
import { Home } from "./home";
import { SubRoute } from "./sub-route";
export default function Root(props) {
return (
<Router>
<Switch>
<Route path="/" exact>
<Home {...props} />
</Route>
<Route path="/sub-route" exact>
<SubRoute />
</Route>
</Switch>
</Router>
);
}
主组件:
import { LocationDescriptor } from "history";
import * as React from "react";
import { useHistory } from "react-router-dom";
import { TestLocationState } from "./sub-route";
export const Home = () => {
const history = useHistory();
return (
<>
<h1>Home</h1>
<button
onClick={() => {
const location: LocationDescriptor<TestLocationState> = {
pathname: "/sub-route",
state: {
name: "STATE PAYLOAD",
},
};
history.push(location);
}}
>
Pass state to sub route
</button>
</>
);
};
子例程组件:
import * as React from "react";
import { useLocation } from "react-router-dom";
export type TestLocationState = {
name: string;
};
export const SubRoute = () => {
const { state } = useLocation<TestLocationState | undefined>();
return (
<>
<h1>Sub Route</h1>
<div>state: {JSON.stringify(state)}</div>
</>
);
};
在虚拟应用程序中,当我单击home组件中调用 history.push()
,使用 state
财产 state
不仅成功地传递给子例程组件,而且如果刷新或硬刷新,状态值仍然可用。
在我的生产应用程序(一个完全独立的应用程序,其中包括上述内容,当然还有很多其他内容)中,状态成功地传递给子例程组件,但在刷新时不会保留。它是 undefined
.
我很困惑是什么导致了我的生产应用程序和测试应用程序的不同行为。这是一件好事吗?思想?
暂无答案!
目前还没有任何答案,快来回答吧!