【问题标题】:react router does not render when the url changesurl更改时反应路由器不呈现
【发布时间】:2021-12-28 04:26:23
【问题描述】:

我在Main 组件中有以下内容;

<Routes>
    <Route path="/forum/*" element={<Forum />} />
</Routes>

这个在Forum组件里面

<Routes>
    <Route path=":topicName" element={<QuestionFeed />} />
</Routes>

当我第一次导航到/forum/programming 时,路由器按预期呈现。但是在点击Link 后,只会更新 URL,组件不会重新渲染。

&lt;Link to="programming"&gt;

为什么路由器在点击链接时不渲染,但我手动访问url时渲染。

"react":            "^17.0.2",
"react-dom":        "^17.0.2",
"react-router-dom": "^6.2.1",

【问题讨论】:

  • 您好,您的问题可以通过 codepen/stackbiz 来说明。它将帮助您澄清问题。 Anw,您的代码看起来不错,我认为问题不是来自 react-route,它可能与钩子/您的组件生命周期有关。

标签: reactjs react-router-dom


【解决方案1】:

已解决

问题出在QuestionFeed 组件中。 状态仅在 useEffect 中更新,由于依赖数组为空,因此仅执行一次。将 url 参数添加到列表中以使其更新状态。

    const { topicName } = useParams();

    useEffect(() => {
        ...
        setQuestions(questions || []);
        ...
        .catch(error => console.log(error));
    }, []); // empty dependency array
    const { topicName } = useParams();

    useEffect(() => {
        ...
        setQuestions(questions || []);
        ...
    }, [topicName]);

【讨论】:

    【解决方案2】:

    您需要尝试使用完整的 url /forums/programming。

    【讨论】:

      【解决方案3】:

      Forum 组件中,您还必须指定父路由 url。您可以从Forum 组件内的match 道具中获取父 url,然后您可以这样做

      <Routes>
        <Route path={`${parentRoute.url}/:topicName`} element={<QuestionFeed />} />
      </Routes>
      

      或者在你的情况下这也应该有效

      <Routes>
        <Route path="/forum/:topicName" element={<QuestionFeed />} />
      </Routes>
      

      基本上你必须在Route 中指定path 的完整路径

      然后你可以使用&lt;Link to="/forum/programming"&gt;这样的链接组件,它应该可以工作

      【讨论】:

        猜你喜欢
        • 2016-12-26
        • 1970-01-01
        • 1970-01-01
        • 2018-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-04
        • 2023-02-03
        相关资源
        最近更新 更多