【发布时间】:2020-12-29 11:27:43
【问题描述】:
我正在尝试使用反应钩子(这是我第一次),但是在使用 useEffect 时出现此错误,例如上面的 componentDidMount:'React Hook useEffect 缺少依赖项:'props'。包括它或删除依赖数组。然而,当 any props 时,'props' 会改变 更改,因此首选的解决方法是在 useEffect 调用之外解构“props”对象,并在 useEffect 中引用那些特定的 props'
我正在尝试向 API 发出 GET 请求,这需要 url 中的一些道具。这是我的代码:
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 和对函数的调用中获得了一个 undefined。
然后我尝试这样做:
useEffect(()=>{
//here is the code like the first one
},[props])
但这会向 api 发出 n 个请求
【问题讨论】:
-
我认为你不需要将 props 放入依赖数组中......
-
是的,但这就是我在第一个代码中所做的,我得到了这个:React Hook useEffect 缺少依赖项:'props'。包括它或删除依赖数组。但是,当 any 道具发生变化时,“道具”会发生变化,因此首选的解决方法是在 useEffect 调用之外解构“道具”对象,并在 useEffect 中引用那些特定的道具
-
也许这会有所帮助? stackoverflow.com/questions/55840294/…
-
是的,这对我有帮助,然后我得到了那个错误
标签: javascript reactjs api react-hooks