Axios调用在ComponentDidMount中运行两次



我使用Axios从我的后端获取数据。我知道在react中,18个严格模式组件被渲染两次。删除严格模式是一种不好的做法,因为它可以帮助您捕获错误。两次获取数据会破坏我的代码,因为我最终得到的另一个令牌与后端存储的令牌不匹配。有没有一种方法可以确保Axios调用只被调用一次?下面的代码。

import React, { Component } from "react";
import axios from "axios";
import history from "../../history";
class Authenticate extends Component {
constructor(props) {
super(props);
this.state = {
token: "",
dataFetched: false,
};
this.getCallBack = this.getCallBack.bind(this);
}
async componentDidMount() {
let { dataFetched } = this.state;
if (!dataFetched) {
try {
await axios({
method: "get",
url: "/users/twitter_login",
}).then((res) => {
if (res.data.boolean) {
this.setState({ dataFetched: true, token: res.data.token });
this.getCallBack(res.data.url);
} else {
history.push({
pathname: "/login",
});
}
});
} catch (error) {
console.log(error);
}
}
}
getCallBack(url) {
history.push(url);
}
render() {
return (
<div>
<img src="http://placekitten.com/g/200/300"></img>
</div>
);
}
}
export default Authenticate;

你可以使用这个自定义钩子或者在class land中使用它

import { useEffect, useRef } from "react"
const useInit = (effect: () => void ) => {
const ref = useRef(false)
useEffect(() => {
if (ref.current) return
ref.current = true
effect?.()
},[])
}
export default useInit

最新更新