我在一个Reaction应用程序中使用了Reaction-Router-Domv6.我有带URL参数的路由.当参数更改时,路径的元素props (这是一个组件)会重新呈现,但在组件中的数据变得不一致之前,将参数作为依赖项的useEffect不会触发,从而导致应用程序崩溃(白屏).我的解决方案是用组件包装我所有的路由元素props ,该组件将参数作为关键字传递给我想要渲染的组件.它工作得很好,但我觉得我不应该这么做.要么是有更合适的解决方案,要么是我以后会遇到我没有预料到的问题.我很感激在这件事上的任何建议.谢谢
下面是我的包装器组件:
const PageWrapper = ({page}) => {
const params = useParams();
const key = JSON.stringify(params);
return <div key={key}>{page}</div>
}
这就是我所有的路由:
<Route
path={`thing_type/:thing_type_id`}
element={
<PageWrapper
page={<ThingTypePage/>}
/>
}
/>
让我的所有路由看起来像这样有点难看和混乱,但它都包含在我的路由文件中,所以我可以处理它.
我try 将参数作为键直接传递给元素属性,但它在Reaction-Router-DomV6中不受支持.
编辑: 只有当我两次导航到同一页面,但参数不同时,问题才会出现.如果在这两个页面之间导航到另一个页面,则不会出现问题.导致崩溃的数据不一致来自于Reaction应用程序中缓存的客户端数据与从服务器获取的数据的混合.这是My Page的缩写示例:
const ThingTypePage = () => {
const {thing_type_id} = useParams();
const {cachedStaticData} = React.useContext(Context);
const [data, setData] = useState(null);
useEffect(() => {
setData(null);
const body = {thing_type_id};
const onSucceeded = (response) => setData(response.data);
const onFailed = (err) => setData(false);
myFetch("myBackendUrlExtension", body, onSucceeded, onFailed);
}, [thing_type_id])
if(data === null) return <div>Loading...</div>;
if(data === false) return <div>Failed to load</div>;
const things = data.instances;
const thingTypeObjectStructure = getThingTypeObjectStructure(cachedStaticData, thing_type_id);
// at this point things = data from previous fetch, when thing_type_id = old_id
// but thingTypeObjectStructure has the updated value, using thing_type_id = new_id
return (
<div key={`ThingTypePage-${thing_type_id}`}>
<ThingsTable
// here 'things' is being rendered with a false assumption of their object structure
// causing crashes (accessing undefined)
things = {things}
structure = {thingTypeObjectStructure}
/>
</div>
)
}