【发布时间】:2020-06-18 12:05:59
【问题描述】:
我的反应应用程序给了我这个警告:
React Hook useEffect 缺少依赖项 要么包含它,要么 移除依赖数组 react-hooks/exhaustive-deps
如果我将 Stateful 组件移动到 useEffect 挂钩内部,那么我的 Button 将无法再访问 setButton。有没有办法解决这个问题?
const [value, setValue] = useState([])
const [isLoading, setLoading] = useState(false)
const [buttonValue, setButton] = useState(false)
这是我的 useEffect Hook
useEffect(() => {
axios.get('http://localhost:5000/').then(res => setValue(res.data))
if (buttonValue === 'delete') {
setLoading(true)
axios.delete('http://localhost:5000/delete').then(() => {
setLoading(false)
setButton(null)
})
} else if (buttonValue === 'create') {
setLoading(true)
axios.post('http://localhost:5000/').then(() => {
setLoading(false)
setButton(null)
})
}
}, [isLoading])
这些是我的按钮
<Form>
<Form.Group>
<Button variant='success' className='button' onClick={() => setButton('create')} id='create'>Create Sales Order</Button>
</Form.Group>
<Form.Group>
<Button variant='danger' className='button' onClick={() => setButton('delete')} id='delete'>Delete Sales Order</Button>
</Form.Group>
</Form>
【问题讨论】:
-
它只是想让你将
buttonValue添加到依赖数组中。使用当前设置,效果只会在挂载时运行,并且当isLoading更改时。但是由于您在挂钩中使用buttonValue,因此警告您应该将其作为依赖项包含在内。
标签: reactjs