Reactjs 反应重复的api响应

Reactjs 反应重复的api响应,reactjs,api,fetch,Reactjs,Api,Fetch,我正在向API发出获取请求,请求成功,但当我将响应记录为console.log时,它会被记录两次 我的组件 const Content = () => { let userId = JSON.parse(localStorage.getItem('user')); fetch(`http://localhost:3000/post/`, { method: 'GET', headers: { 'Content-Type': 'applica

我正在向API发出获取请求,请求成功,但当我将响应记录为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>
  );
};

为什么会有两个响应?

因为每次渲染时都会调用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)
      }
    );
}, []);
在其他情况下,您可能有两个或多个组件。 防止两次提取,并为所有人访问一次。我建议使用react查询。 你可以

useQuery('data', fetch())
useQuery('data', fetch())