【发布时间】:2021-10-25 00:34:25
【问题描述】:
我在我的 React 字典项目中使用 React Router,由于某种原因,在我运行 history.push()(使用 react-router 中的 useHistory 挂钩)后,我的页面没有重新呈现。我有一个搜索栏,我使用此功能转到一个新链接。
const KeyPressHandler: KeyboardEventHandler<HTMLInputElement> = (event) => {
const { value } = event.currentTarget;
if ((event.code === "Enter" || event.code === "NumpadEnter") && value.length)
history.push(`/dictionary/${value}`);
};
};
我的App 组件如下所示:
const App = (): JSX.Element => {
...
return (
...
<Route path="/dictionary" component={DictionaryEntryPage} />
...
);
};
这就是DictionaryEntryPage 组件:
const DictionaryEntryPage = (): JSX.Element => {
const [wordData, setWordData] = useState<WordData[] | undefined | null>(undefined);
// useRouteMatch is imported from react-router
const match = useRouteMatch<{ requestedWord: string }>("/dictionary/:requestedWord");
useEffect(() => {
const { requestedWord } = match?.params ?? {};
if (requestedWord) {
(async () => {
const data = await parseWordData(requestedWord);
setWordData(data || null);
})();
} else setWordData(null);
}, []);
const wordDataEls = wordData ? wordData.map((data, i) => <Word {...data} key={i} />) : <Loading />;
...
}
让我知道我应该在问题中添加/删除什么,如果有人想看的话,here 是一个演示链接。
【问题讨论】:
-
你能发布你的应用组件的完整代码吗?
-
或者你的仓库的链接,如果它在 GitHub 上的话。我怀疑您在
DictionaryEntryPage中的 useEffect 中缺少依赖项。我相信您可能需要将match作为依赖项,以在比赛发生变化时强制该效果重新运行。但我真的很想看看 repo 以确定。如果您尝试这样做并解决了它,我很乐意写一个答案来解释原因 -
记录您的
match或requestedWord并检查它是null或{} -
没关系,我去找到了 repo 并确认您的问题是缺少 useEffect 中的依赖项。我会为你整理一个答案。
标签: javascript reactjs react-router