我认为我在正确使用useEffect方面有些不了解。在LicenseKeyGenerator.js中,我有一种效果,我只想在更改“ machineId”或“ customerId”时触发,但是反应小子大喊大叫我如何需要对“ updateKeys”的依赖,但是当我添加该引用时,它会导致无限环。
Linter输出: React Hook useEffect缺少依赖项:'updateKeys'。包括它或删除依赖项数组
当“ updateKeys”依赖项不存在时,它似乎可以按照我期望的方式工作,但是这种错误使我相信我在错误地构造此代码。
我应该如何重组此代码,以使短毛猫离开我一个人?
为什么“ updateKeys”应该只是我在任何地方都没有更改的函数时会触发useEffect?
仅在“ updateKeys”更改时才触发吗?LicenseContext.js
const LicenseContext = createContext();
export const LicenseContextProvider = (props) => {
const [keys, setKeys] = useState([])
const updateKeys = (machineId, customerId) => {
//just a wrapper around fetch()
return apiPost("/api/licensekey/managementdata", {
body: {
"machineHexId": machineId,
"customerId": customerId
}
})
.then(json => {
setKeys(json.Data.KeyList)
})
}
return (
<LicenseContext.Provider value={{ keys, updateKeys }}>
{props.children}
</LicenseContext.Provider>
)
}
export function useLicenseContext() {
return useContext(LicenseContext);
}
LicenseKeyGenerator.js
const LicenseKeyGenerator = () => {
const { updateKeys } = useLicenseContext();
const [machineId, setMachineId] = useState("")
const [customerId, setCustomerId] = useState("")
useEffect(() => {
if(machineId && machineId.length === 4 && customerId && parseInt(customerId) >= 0) {
updateKeys(machineId, customerId)
}
}, [machineId, customerId])
//other code left out because it doesn't seem relevant to the issue
}
License.js
const License = () => {
return (
<LicenseContextProvider>
<LicenseKeyGenerator />
<LicenseManagement />
</LicenseContextProvider>
);
}