我尝试使用React Hooks(这是我第一次使用),但当像componentDidMount一样使用useEffect时,会出现以下错误:“React Hook useEffect的依赖项缺失:'props'。要么将其包含在内,要么删除依赖项数组。但是,'props'将在任何 prop更改时改变,因此首选修复方法是在useEffect调用外部解构'props'对象,并在useEffect中引用那些特定的props。
我正在尝试向API发出GET请求,需要在url中传递一些props。这是我的代码:
function SomeComponent(props) {
const [data, setData] = useState({});
const [loading, setLoading] = useState(true);
const [hasError, setErrors] = useState(false);
useEffect(() => {
async function fetchData() {
try {
let response = await Axios.get( `/some-url/${props.obj.id}/abc`,
);
let { data } = response.data;
setData(data);
setLoading(false);
props.totalStats({data });
} catch (error) {
setErrors(error);
setLoading(false);
}
}
fetchData();
}, []);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
我一直在寻找并尝试这些解决方案,但它们对我无效:
const { id } = props.obj.id;
const {totalStats} = props.totalStats
useEffect(()=>{
//Here is the code
//I replace the $ {props.obj.id} by the id and the function props.totalStats by //totalStats
},[id,totalStats]
我用那种方法得到了id和调用函数的未定义。
然后我尝试这样做:
useEffect(()=>{
//here is the code like the first one
},[props])
但这会向 API 发送n个请求