有人能帮我解决这个错误吗?在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 hook/exaustive deps";
这是因为无论何时使用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]);
将fetchData
作为参数传递给useEffect
useEffect(() => {
fetchData();
}, [fetchData]);