Axios 在加载页面时进行了双重的 POST 请求。

huangapple go评论59阅读模式
英文:

Axios making double post request while loading page

问题

当我使用Postman进行此POST请求时,它正常工作,但在这种情况下,我的Django服务器显示已经进行了两个请求,数据也被记录了两次。我正在使用JWT令牌,如果它与某种方式相关...

  const controller = new AbortController();
  const [isLoading, setIsLoading] = useState(true);
  const [userData, setUserData] = useState({
    name: "",
    username: "",
    email: ""
  });

  const getData = () => {
    axiosInstance.post("/api/detail/", {
      signal: controller.signal
    })
    .then((data) => {
      setUserData({
        name: data.data.name,
        username: data.data.username,
        email: data.data.email
      });
      console.log(data); // 这个数据被记录了两次
      setIsLoading(false);
      return controller.abort();
    })
    .catch((err) => {
      console.log("错误是", err);
    });
    return controller.abort();
  }

  useEffect(() => {
    getData();
  }, []);
英文:

When I made this post request with postman it works fine but in this case my django server shows two requests are made and data is also logged twice. I am using jwt tokens if it is related somehow ...

  const controller = new AbortController();
    const [isLoading , setIsLoading] = useState(true)
    const [userData , setUserData] = useState({
        name:"",
        username:"",
        email:""
    })

    const getData = () =>{
      axiosInstance.post("/api/detail/" , {
        signal:controller.signal
      })
      .then((data) =>{
        setUserData({
            name : data.data.name,
            username : data.data.username,
            email : data.data.email
          }
          )
          console.log(data) // this data is logged twice 
          setIsLoading(false)
      return controller.abort()

      }).catch((err)=>{
          console.log("error is" , err)
      })
      return controller.abort()
    }
    useEffect(()=>{
        getData()
    } ,[])

答案1

得分: 2

你可能正在使用StrictMode。检查你的主文件(index.js,main.js),看看组件是否包装成这样:

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

有关更多详细信息,请参阅此答案:https://stackoverflow.com/questions/61254372/my-react-component-is-rendering-twice-because-of-strict-mode/61897567#61897567

英文:

You are probably using the StrictMode. Check your main file (index.js, main.js) and see if the component is wrapped like this:

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

For more details about that, you can see this answer: https://stackoverflow.com/questions/61254372/my-react-component-is-rendering-twice-because-of-strict-mode/61897567#61897567

答案2

得分: 1

useEffect在开发模式下会被调用两次,如果启用了严格模式,它将在生产模式下仅运行一次。

useEffect中不应尝试使用useRefif语句来使其仅触发一次,或者移除StrictMode,因为React在开发中有意重新挂载组件,以帮助您找到错误,因此useEffect会被调用两次。更多信息请参考此处:https://stackoverflow.com/a/72238236/12083049

我强烈建议使用数据获取库,例如react-queryswr来处理API。

swr示例:

import useSWR from 'swr'

function Profile() {
  const { data, error, isLoading } = useSWR('/api/user', fetcher)

  if (error) return <div>加载失败</div>
  if (isLoading) return <div>加载中...</div>
  return <div>你好{data.name}</div>
}
英文:

useEffect is called twice in the development mode and will only run once on production if strict mode is enabled.

You shouldn't try to use those technics with useRef and if statements in useEffect to make it fire once, or remove StrictMode because react intentionally remounts your components in development to help you find bugs and because of that use effect is called twice. Read here for more information: https://stackoverflow.com/a/72238236/12083049

I would highly recommend using a data-fetching library like react-query or swr to work with API.

swr example:

import useSWR from &#39;swr&#39;
 
function Profile() {
  const { data, error, isLoading } = useSWR(&#39;/api/user&#39;, fetcher)
 
  if (error) return &lt;div&gt;failed to load&lt;/div&gt;
  if (isLoading) return &lt;div&gt;loading...&lt;/div&gt;
  return &lt;div&gt;hello {data.name}!&lt;/div&gt;
}

huangapple
  • 本文由 发表于 2023年3月4日 02:19:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75630591.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定