【问题标题】:How to re-render component on url change如何在 url 更改时重新渲染组件
【发布时间】:2020-08-23 08:33:36
【问题描述】:

在我的应用程序的 GroupInfo 组件中,有一个 useEffect 应该在来自 props 的匹配更改时触发。但事实并非如此。 useEffect的代码如下。

useEffect
(
    () =>
    {
        try
        {
            const runEffect = async () =>
            {
                const _id = match.params.id;
                const response = await api.get
                (
                    "/groupidindex",
                    {
                        params:
                        {
                            _id
                        }
                    }
                );
                setGroup (response.data);
            }
            runEffect();
        }
        catch (error)
        {
            throw new Error (error);
        }
    },
    [match]
)

而设置链接的那段代码如下。

<Link key = {index} to = {match.url.concat ("/"+group._id)}>

App.js文件中组件的声明如下。

<Route path = "/groups/:id/:id" component = {GroupInfo}/>

当路径满足要求时GroupInfo组件不渲染,路径改变时不重新渲染。但是,当我重新加载页面时,它会渲染/重新渲染。我之前在同一个应用程序的另一个组件中使用了一个在 url 更改时更改的 useEffect,它工作正常。

【问题讨论】:

  • 您确定match 对象发生了变化,还是只是它的某些属性发生了变化?除此之外,您的 try...catch 块毫无用处。这段代码中永远不会有它会捕获的错误。
  • @Thomas 匹配对象的某些属性肯定会发生变化,例如 url。如果对象本身“改变”,我不确定。但是,我尝试在 useEffect 中将“[match]”替换为“[match.url]”,但没有任何改变。现在,关于 try...catch,我在那里使用它是因为应用程序后端有一条警告消息。消息是:“UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。”我从来没有找到答案。

标签: reactjs react-hooks render use-effect


【解决方案1】:

您确定 match 对象发生了变化,还是只是它的某些属性发生了变化?

除此之外,您的 try...catch 块毫无用处。这段代码中永远不会有它会捕获的错误。

const runEffect = async () =&gt; {...} 可能会引发语法错误,但不会引发try..catch 可以处理的运行时错误。 runEffect() 可以返回一个被拒绝的 Promise,但你的 try..catch 也不会处理这个问题。除非你await runEffect()

我发现在 Promise 链中重新throw new Error(error); 毫无意义,所有这一切都会让你在控制台中输入一个Uncaught (in promise) ... 错误。

但是,我尝试在 useEffect 中将“[match]”替换为“[match.url]”,但没有任何改变。

对不起,我不知道;也许这里有点太晚了。但最终你只关心 id-param,不是吗?

我会这样写:

// you can put these outside the component itself as 
// they don't rely on anything but the passed arguments:
const getGroup = async (_id) => {
  const response = await api.get("/groupidindex", {
    params: {
      _id
    }
  });

  return response.data;
}

const logError = error => {
  console.error(error) 
};

// in the component
useEffect(() => {
  getGroup(match.params.id).then(setGroup).catch(logError);
}, [match.params.id])

现在,关于 try...catch,我在那里使用它是因为应用程序的后端有一条警告消息。消息是:“UnhandledPromiseRejectionWarning:未处理的承诺拒绝。

如果您不关心错误并且只是不想要错误消息,您可以使用function noop(){} .catch() 错误。

【讨论】:

    猜你喜欢
    • 2021-01-27
    • 2021-07-08
    • 1970-01-01
    • 2023-03-28
    • 2022-01-17
    • 2022-11-12
    • 1970-01-01
    • 2017-10-26
    • 2023-03-20
    相关资源
    最近更新 更多