【问题标题】:React duplicate api response反应重复的 api 响应
【发布时间】:2021-05-22 20:54:51
【问题描述】:

我正在向 API 发出 fetch 请求,请求成功,但是当我 console.log 响应时,它会被记录两次。

我的组件

const Content = () => {
  let userId = JSON.parse(localStorage.getItem('user'));

  fetch(`http://localhost:3000/post/`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'authorization': 'Bearer ' + userId.token,
      },
    }).then(response => response.json())
    .then(data => {
      console.log(data)
      }
    );
    
  return (
    <Container>
      <Card>
        <Name></Name>
        <Time></Time>
        <Image></Image>
        <Text></Text>
      </Card>
    </Container>
  );
};

控制台会记录:

(13) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

(13) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

为什么我会得到两个响应?

【问题讨论】:

    标签: reactjs api fetch


    【解决方案1】:

    因为您在每次渲染时都调用 fetch。使用 useEffect 钩子来防止它。

    React.useEffect(() => {
      let userId = JSON.parse(localStorage.getItem('user'));
    
      fetch(`http://localhost:3000/post/`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'authorization': 'Bearer ' + userId.token,
          },
        }).then(response => response.json())
        .then(data => {
          console.log(data)
          }
        );
    }, []);
    

    在其他情况下,您可能有两个或更多组件。 以防止获取两次并为所有人访问一次。我建议使用反应查询。 你可以

    useQuery('data', fetch())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-19
      • 1970-01-01
      • 2015-03-02
      • 1970-01-01
      • 2020-08-12
      • 2021-03-29
      相关资源
      最近更新 更多