【问题标题】:How do I fire off a react action when url changes?url 更改时如何触发反应动作?
【发布时间】:2021-08-06 01:47:36
【问题描述】:

所以我正在构建一个用户可以查看彼此个人资料的网站。我有一个配置文件组件,我想根据用户 ID 显示配置文件。我将这些用户 ID 作为 url 参数发送。

我的问题是,如果我从另一个用户个人资料切换到我的个人资料,我的 getProfileById 不会触发(我有一个我的个人资料按钮,可以直接将经过身份验证的用户的 id 发送到 url 参数)。我想在 url 更改时触发我的操作,我该怎么做?

这是我的getProfileById 操作代码:

export const getAllProfileById = (userId) => async dispatch => {
    dispatch({ type: "CLEAR_PROFILE" });
    try {
        const res = await axios.get(`/api/profile/${userId}`);

        dispatch({
            type: "GET_PROFILE",
            payload: res.data.data
        })
    } catch (error) {
        dispatch({
            type: "PROFILE_ERROR",
            payload: { msg: error.response.statusText, status: error.response.status }
        })
    }
}

这是我在个人资料组件中调用getProfileById 的方式

 useEffect(() => {

        if (!profile) {
            dispatch(getAllProfileById(id));
        }
    }, [dispatch])

【问题讨论】:

  • 你试过useLocation 吗? reactrouter.com/web/api/Hooks/uselocation
  • 你在用react-router-dom吗?
  • 你能告诉我们带url参数的组件的路由吗? (例如<Route path="/tweet/:id" exact component={TweetDetail} />
  • 我尝试将位置放入 useEffect 但不起作用
  • 是的,我正在使用 react-router-dom

标签: javascript reactjs react-redux react-hooks react-router-dom


【解决方案1】:

基于评论部分 - 您正在使用 react-router-dom - 您可以使用 useParams 挂钩来捕获与 useEffect 组合的更改,请参阅文档:

useParams 返回 URL 参数键/值对的对象。用它来访问当前<Route>中的match.params

查看可能的简化工作思路:

const Profile = () => {
  const { id } = useParams() // destructure the id param from the URL

  useEffect(() => {
     // here you can see a logging step once id is changing
     // based on the given dependency array
     console.log(id)

     // also you can dispatch your action as
     dispatch(getAllProfileById(id))
  }, [id])

  return <> your component's code </>
}

当然,如果 URL 中有不同的参数名称,只需将其从 id 更改为正确的名称即可。

【讨论】:

  • 太棒了,乐于助人!
猜你喜欢
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-10
  • 2022-01-24
  • 1970-01-01
相关资源
最近更新 更多