【问题标题】:React: URL Profile ID doesn't match (match.params.id)反应:URL 配置文件 ID 不匹配(match.params.id)
【发布时间】:2020-10-18 14:03:45
【问题描述】:

所以每当我点击查看个人资料链接时

 <Link to={`/profile/${_id}`} className="btn btn-primary">
                View Profile
 </Link>

它在 URL 中显示配置文件的用户 ID,这是好的。

但每当我单击它以将其与此按钮匹配时,我都会收到错误。

const Profile = ({ getProfileById, match }) => {
useEffect(() => {
    getProfileById(match.params.id);
}, [getProfileById]);

return <div>test</div>;

};

我进入我的控制台

React Hook useEffect has a missing dependency: 'match.params.id'. Either include it or remove the dependency array

这就是我的应用 Js 中的内容。

   <Route
         exact
         path="/profile/:id"
         component={Profile}
     />

我认为它与我单击的按钮的 URL 不匹配。

在 Redux Devtools 中,它只返回一个配置文件错误。

【问题讨论】:

  • 使用 useEffect 依赖数组参数旨在包含效果应监视更改以确定何时运行的变量。 linter 告诉你传递它[match.params.id]
  • 我该怎么做?在我遵循的教程中,它具有相同的代码,但与它们配合得很好。
  • 我总是使用这个评论(eslint-disable-next-line react-hooks/exhaustive-deps)并且工作正常。但这一个变得非常奇怪。

标签: reactjs react-redux react-router


【解决方案1】:

在这种情况下,产生警告的 linter 规则:React Hook useEffect has a missing dependency: 'match.params.id'. Either include it or remove the dependency array,告诉您您有另一个依赖项。改用这个:

const Profile = ({ getProfileById, match }) => {
useEffect(() => {
    getProfileById(match.params.id);
}, [getProfileById, match.params.id]);

return <div>test</div>;

linter 不会探索您的整个应用程序以确定 match 的使用位置和方式。它也不知道你将来打算如何使用它,因此它要求你把它和getProfileId一起放在依赖数组中。

如果您已导入 getProfileId 或将其放在组件外部而不是将其作为道具传递,您可以安全地从依赖项中删除 getProfileId。所有这些都是说弄清楚数组内部的内容需要一些额外的理解。 Dan Abramov 写了一篇很棒的 blog post,它帮助我了解何时以及如何使用依赖数组。如果您发现 Dan 的帖子有点过于宽泛,因为它涉及编写弹性组件的更笼统的概念,这个 post 可能是一个不错的起点。

【讨论】:

  • 我已经这样做了,在我的 redux devtools 中它返回配置文件 null。和我的减速器配置文件错误。
  • 好的,所以听起来问题与 linter 警告无关。 getProfileById 长什么样子?
  • 另外,你可以通过检查你的 react devtools 中的 prop(或者甚至只是控制台记录 match.params.id)来排除你所说的 think it doesn't match with the URL to the button
  • 这是我的 getProfileById // 按 ID 获取配置文件 export const getProfileById = (userId) => async (dispatch) => { try { const res = await axios.get(/api/profile/user/${userId}); dispatch({ type: GET_PROFILE, payload: res.data, });
【解决方案2】:

我设法弄清楚出了什么问题。它在我的 API 中。我正在尝试在我的 API 中点击 .get

但在我的 API 中,它显示了补丁。

然后我将其更改为获取。

它有效。

【讨论】:

    猜你喜欢
    • 2019-06-10
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    相关资源
    最近更新 更多