当我删除 , []( 依赖项时,没关系,但是创建一个无限循环 - 有了它,我遇到了此错误,其他元素无法正常工作。
但是,我该如何解决它?我不知道为什么会出现以下错误:
谢谢
Line 74:8: React Hook useEffect has a missing dependency: 'database'. Either include it or remove the dependency array. You can also do a functional
update 'setDatabase(d => ...)' if you only need 'database' in the 'setDatabase' call react-hooks/exhaustive-deps
<小时 />function AddOrder(props) {
const [step, setStep] = useState(1)
const [redirect, setRedirect] = useState(false)
const [database, setDatabase] = useState({
clients: [],
orders: [],
client: [],
products: [],
subProducts: [],
filteredSubProducts: [],
useEffect(() => {
axios.get('http://127.0.0.1:8000/api/clients')
.then(res => {
setDatabase({...database, clients: res.data})
})
axios.get('http://127.0.0.1:8000/api/orders')
.then(res => {
setDatabase({...database, orders: res.data})
})
axios.get('http://127.0.0.1:8000/api/products')
.then(res => {
setDatabase({...database, products: res.data})
})
axios.get('http://127.0.0.1:8000/api/subProducts')
.then(res => {
setDatabase({...database, subProducts: res.data})
})
}, []);
我会接受警告的建议并使用setDatabase
的功能更新形式:
function AddOrder(props) {
const [step, setStep] = useState(1)
const [redirect, setRedirect] = useState(false)
const [database, setDatabase] = useState({
clients: [],
orders: [],
client: [],
products: [],
subProducts: [],
filteredSubProducts: [],
});
useEffect(() => {
axios.get('http://127.0.0.1:8000/api/clients')
.then(res => {
setDatabase(database => ({...database, clients: res.data}))
})
axios.get('http://127.0.0.1:8000/api/orders')
.then(res => {
setDatabase(database => ({...database, orders: res.data}))
})
axios.get('http://127.0.0.1:8000/api/products')
.then(res => {
setDatabase(database => ({...database, products: res.data}))
})
axios.get('http://127.0.0.1:8000/api/subProducts')
.then(res => {
setDatabase(database => ({...database, subProducts: res.data}))
})
}, []);
}
Josh Wilson 的替代解决方案:在依赖项数组中包含database
。
function AddOrder(props) {
const [step, setStep] = useState(1)
const [redirect, setRedirect] = useState(false)
const [database, setDatabase] = useState({
clients: [],
orders: [],
client: [],
products: [],
subProducts: [],
filteredSubProducts: [],
});
useEffect(() => {
axios.get('http://127.0.0.1:8000/api/clients')
.then(res => {
setDatabase({...database, clients: res.data})
})
axios.get('http://127.0.0.1:8000/api/orders')
.then(res => {
setDatabase({...database, orders: res.data})
})
axios.get('http://127.0.0.1:8000/api/products')
.then(res => {
setDatabase({...database, products: res.data})
})
axios.get('http://127.0.0.1:8000/api/subProducts')
.then(res => {
setDatabase({...database, subProducts: res.data})
})
}, [database]);
}