[英]Can I get the updated value of a variable in a closure?
Note: React App.注意:反应应用程序。
I'm not sure if this is possible, but I have a function that sets up an object with keys that hold a set of numbers and returns an updater function.我不确定这是否可行,但我有一个 function,它设置了一个 object,其密钥包含一组数字并返回一个更新程序 function。
I have 3 components that call this on click on a number matrix, and if I log the result of the return of that function call then and there, I get the updated object of set values back.我有 3 个组件在单击数字矩阵时调用它,如果我记录 function 调用的返回结果,我会得到更新的 object 设置值。
function App() {
const fn = (keys) => {
const obj = {};
// loop through keys to create -> obj = { [key]: new Set() };
const updater = (num, key) => {
obj[key].has(num) ? obj[key].delete(num) : obj[key].add(num);
return obj;
}
return updater;
}
// initialize
const updateFn = fn(['key1', 'key2', 'key3']);
// correctly update the sets values and return ALL updates on change
const updateAndLog = (num, key) => console.log(updateFn(num, key))
// But when I try to call it from elsewhere in a callback to send to an api such as:
const handleSend = () => {
console.log(updateFn(0, 'key1')) // { key1: {0}, key2: {}, key3: {} };
}
return (
<>
<Component index={1} handleUpdate={updateAndLog} .. />
<Component index={2} handleUpdate={updateAndLog} .. />
<Component index={3} handleUpdate={updateAndLog} .. />
<button onClick={handleSend}>Send Data</button>
</>
)
}
It returns empty, and with a new object with just that 0 stored in the first key.它返回空,并带有一个新的 object,而第一个键中只存储了 0。 Now, I know I could store these in state as I go, but I'm trying to avoid that in this scenario.
现在,我知道我可以将这些存储在 state 中,就像我的 go 一样,但在这种情况下我试图避免这种情况。
If you have any recommendations on how this might be achieved would be great!如果您对如何实现这一目标有任何建议,那就太好了!
Thanks谢谢
Your updateFn
gets recreated every time the component renders.每次组件呈现时都会重新创建您的
updateFn
。
So you could do this to prevent it from being recreated.所以你可以这样做来防止它被重新创建。
const updateFnRef = useRef(fn(['key1', 'key2', 'key3']))
const updateFn = updateFnRef.current;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.