我正在嘗試在 React 和 Node.js 中創建我的專案。我在組件內使用 useEffect 鉤子。在這個 useEssect 中,前端向后端發出請求,以獲取一些資訊。我傳遞給呼叫的一些資訊來自元素的滴鉆。出現以下警告:
Line 20:8: React Hook useEffect has a missing dependency: 'ans.group.id'. Either include it or remove the dependency array react-hooks/exhaustive-deps
下面是組件代碼:
const GFiles = (ans) => {
const g = useContext(PopupContestG);
const v = useContext(PopupContest);
const [file, setFile] = useState([])
const act = ans.obj === 'h' ? v : g;
useEffect(() => {
let id = ans.group.id
axios.post("http://127.0.0.1:5050/file/getfilesbygroup",{group:id})
.then(res => {
setFile(res.data);
})
.catch(err => console.log(err))
}, [])
return (<>
<div className="gFiles">
<h3 style={{'textAlign': 'left'}}>File list</h3>
<div className="sidesaparator"></div>
<div className="fileContainer">
{file.map(f=>{
return <SFile key={f._id} name={f.name} img={f.extension} ident={f._id} />
})}
<button className="buttSendA" onClick={() => act.setPopup(1)}>ADD File</button>
<Link to="/edit" className="buttSendA12">Enter Group Workspace</Link>
</div>
</div>
</>)
}
在useEffect中作為第二個引數使用的空陣列中,VSCode放了一條黃線,所以不知道是什么問題。我試圖弄清楚如何擺脫這個問題,但是在堆疊溢位時,有人解決了在 useEffect 中宣告變數的問題。我嘗試過,但對我來說也沒有任何意義,并且沒有奏效。有人可以幫我解決這個問題嗎?它會影響代碼執行本身還是只是反應說更好做的事情?謝謝
uj5u.com熱心網友回復:
由于您的 ans.group.id 可以更改 const act = ans.obj === 'h' ? v : g;,因此 react 會告訴您需要將其包含在依賴項陣列中。如果您只想運行此使用效果一次,則可以簡單地忽略此警告。如果您想在 ans.obj 每次更改時重新運行此 useEffect,請將其包含在陣列中。要抑制它,請在 // eslint-disable-next-line react-hooks/exhaustive-deps
上面 添加
}, [])
useEffect(() => {
let id = ans.group.id
axios.post("http://127.0.0.1:5050/file/getfilesbygroup",{group:id})
.then(res => {
setFile(res.data);
})
.catch(err => console.log(err))
}, [ans.group.id]) //<-- Run this code first time and every time ans.group.id is changed
useEffect(() => {
let id = ans.group.id
axios.post("http://127.0.0.1:5050/file/getfilesbygroup",{group:id})
.then(res => {
setFile(res.data);
})
.catch(err => console.log(err))
// eslint-disable-next-line react-hooks/exhaustive-deps //<-- Ignore warning
}, []) //<-- Run this only once, even if ans.group.id changed.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/370893.html
標籤:反应
