有人可以帮助我解决此错误吗?在 useEffect 中,我调用一个函数,该函数发出请求并以redux状态插入响应。
import React, { useEffect, useState } from "react";
import { BrowserRouter as Router, Switch, Route} from "react-router-dom";
import { useDispatch, useSelector } from 'react-redux'
import { actions } from './actions/actions'
import { I18nProvider } from './i18n'
import axios from 'axios'
import Home from './views/home/home';
import Page1 from './views/page1/page1';
import Page2 from './views/page2/page2'
import Page3 from './views/page3/page3'
const App = () => {
const [isLoading, setIsLoading] = useState(true)
const localeDefault = useSelector(state => state.audioGuideReducers.lang)
const dispatch = useDispatch()
const setDataRedux= (data) => dispatch(actions.setDataRedux(data))
useEffect(() => {
fetchData();
}, []);
const fetchData = async () => {
await axios.get('https://link-api.com/alldata')
.then((response) => {
setDataRedux(response.data.data)
setIsLoading(false)
})
.catch( (error) => {
console.log(error.message);
})
}
return (
<I18nProvider locale={localeDefault}>
<Router>
{
isLoading ?
<h1> Loading... </h1>
:
<Switch>
<Route path="/page3/:id" component={Page3} />
<Route path="/page2" component={Page2} />
<Route path="/page1" component={Page1} />
<Route path="/" component={Home} />
</Switch>
}
</Router>
</I18nProvider>
);
}
export default App
尽管应用程序正在“运行”,但我想解决出现的以下警告: “ React Hook useEffect缺少依赖项:'fetchData'。包括它或删除依赖项矩阵react-hooks / exaustive-deps ”
答案 0 :(得分:1)
将fetchData
作为参数传递给useEffect
useEffect(() => {
fetchData();
}, [fetchData]);
答案 1 :(得分:1)
这是因为无论何时使用useEffect
以及是否使用useEffect之外的内容。 UseEffect需要确保何时更新何时不更新,这就是为什么需要在其依赖项中传递它:
useEffect(() => {
fetchData();
}, [fetchData]);
const fetchData = async () => {
await axios.get('https://link-api.com/alldata')
.then((response) => {
setDataRedux(response.data.data)
setIsLoading(false)
})
.catch( (error) => {
console.log(error.message);
})
}
如果只需要在useEffect
内,最好将fetchData
放在useEffect
内:
const setDataRedux = React.useCallback((data) => dispatch(actions.setDataRedux(data)), [])
useEffect(() => {
const fetchData = async () => {
await axios.get('https://link-api.com/alldata')
.then((response) => {
setDataRedux(response.data.data)
setIsLoading(false)
})
.catch( (error) => {
console.log(error.message);
})
}
fetchData();
}, [setDataRedux]);