如何在 url 更改时重新渲染组件

How to re-render component on url change

在我的应用程序的 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的代码如下。

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

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

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

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

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

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

const runEffect = async () => {...} 可能会抛出语法错误,但没有 try..catch 可以处理的运行时错误。 runEffect() 可以 return 一个被拒绝的 Promise,但是你的 try..catch 也不会处理那个。除非你 await runEffect().

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

I tried, however, substitute "[match]" with "[match.url]" in the useEffect and nothing changed.

对不起,我不知道;也许在这里有点太晚了。但最终你只关心 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])

Now, concerning the try...catch, I used it there because of a warning message in the application's backend. The message was: "UnhandledPromiseRejectionWarning: Unhandled promise rejection.

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

错误