【问题标题】:code using useParams, useEffect and useState hooks使用 useParams、useEffect 和 useState 钩子的代码
【发布时间】:2020-12-08 12:49:50
【问题描述】:

谁能告诉我使用钩子的等效代码:

componentDidMount() {
  const { match: { params } } = this.props;

  axios.get(`/api/users/${params.userId}`)
    .then(({ data: user }) => {
      console.log('user', user);

      this.setState({ user });
    });
}

【问题讨论】:

  • 我错过了顶部的这一行 ---componentDidMount() { const { match: { params } } = this.props; ---

标签: reactjs react-hooks


【解决方案1】:

将您的类组件与带有钩子的功能组件相匹配的确切功能如下:

import * as React from "react";
import { useParams } from "react-router-dom";

const Component = () => {
   const { userId } = useParams();
   const [state, setState] = React.useState({ user: null });
   
   React.useEffect(() => {
      axios.get(`/api/users/${userId}`)
         .then(({ data: user }) => {
            console.log('user', user);
            setState({ user });
         });
   }, []);
}

带有空依赖数组的React.useEffect(() => {}, []) 与componentDidMount 生命周期方法的工作方式基本相同。

React.useState 钩子返回一个带有state 的数组和一个更新状态setState 的方法。

参考资料: https://reactjs.org/docs/hooks-state.html https://reactjs.org/docs/hooks-effect.html

顺便说一句,@Yoshi 指出:

提供的 sn-p 容易出错,“移动到钩子”sn-p 将出现与示例中相同的错误。例如,由于请求在componentDidMount 中,如果userId 发生更改,它将不会触发获取userId 的用户数据。为了确保这在钩子中有效,您需要做的就是在 useEffect... 的依赖数组中提供 userId...

   const latestRequest = React.useRef(null);
  
   React.useEffect(() => {
      latestRequest.current = userId;

      axios.get(`/api/users/${userId}`)
         .then(({ data: user }) => {
            if (latestRequest.current == userId) {
               setState({ user });
            }
         });
   }, [userId]);

【讨论】:

  • 我认为效果需要userId作为依赖。
  • 如果我们要解决 OP 的问题,我们可以看到它在 componentDidMount 中被调用,如果我们将 userId 作为依赖项,如果 prop 要更新,它会匹配得更多重新获取。
  • 是的,但就目前而言,这将触发react-hooks/exhaustive-deps lint 规则。另外我认为这是一个错误,如果 url 更改并包含新的 userId,那么效果肯定应该重新运行吗?
  • 您在一个容易出错的应用程序中是对的,它应该在新的userId 上重新运行,并使用useRef 和unmount 返回函数来确保@987654341 的重新运行@ 不会用过时的数据更新状态。但他们的问题具体是如何在 hooks 中实现他们的代码。
  • 你说得对,应该加上,有点像带钩子的枪,尤其是异步请求!
猜你喜欢
  • 1970-01-01
  • 2020-06-22
  • 2020-10-11
  • 2020-09-02
  • 2020-08-15
  • 2021-08-18
  • 2021-12-01
  • 1970-01-01
  • 2020-02-19
相关资源
最近更新 更多