useParams不能与useState (React hooks)一起工作



我试图制作一个动态变量的组件,该变量根据特定的路由而变化。我使用useParams提取两个变量,如gameName和taskNumber。我还设置了状态,以便使用这两个参数进行提示更改。然而,我没有运气让它工作。我也试过useEffect。我注意到状态保持与初始值相同。因为每个游戏都有不同的任务,它们有不同的提示,所以我想使用条件语句来传递这些提示。

当前路径为/timesup/:gameName/:taskNumber

const FailScreen = () => {
const { gameName, taskNumber } = useParams();
const [prompt, setPrompt] = useState("");
if (gameName === "zoomchat") {
if (taskNumber === 1) {
setPrompt("[mute callers]");
} else {
setPrompt("answers");
}
}
return (
<div>
<PromptBox
title="Time's Up!"
msg={`Oh no! You didn’t find all the ${prompt}`}
/>

<Link to="/">
<Button/>
</Link>
</div>
);
};

理想情况下,我不想硬编码提示符。它存在于每款游戏的另一个兄弟组件中。我不知道怎么把这些信息提取出来。我试过使用econtext,但它也不起作用。

你的组件FailScreen看起来很好。您只需要将此组件放入/timesup/:gameName/:taskNumber路径的Router组件中。

那么,它应该是这样的:

<Route path="/:id/about">
<FailScreen />
</Route>

最新更新