如何更新React函数返回的值(useState实现) [英] How to update value returned by function React (useState implementation)
问题描述
比方说,我有这样的东西,函数返回值和setter函数,每次调用它时,如何正确实现setter函数以更新返回值?(例如useState的返回值和updater函数)
Let's say I have such a thing, function returning value and setter Function, how Can I implement the setter function correctly to update returned value , every time it is called? (like useState's returned value and the updater function)
const myFunction = (initialValue) => {
let value = initialValue;
const setterFunction = (newValue) =>{
value= newValue;
}
forceRerender() //function that forces re-renders
return [value,setterFunction];
}
const [myValue,updaterFunc] = myFunction('someValue');
updaterFunc('newValue'); // myValue's new Value should be 'newValue'
推荐答案
如果您要重新实现React的实现方式,则必须让setter函数导致整个块再次运行-类似于以下内容:
If you're trying to re-implement how React does it, you would have to have setter functions result in the whole block running again - something like the following:
const state = [];
const App = () => {
let stateIndex = 0; // This variable keeps track of the sequential calls to `myFunction`
// (Needed if myFunction gets called multiple times)
const myFunction = (initialValue) => {
// Assign initial value if it doesn't exist yet
if (!state.hasOwnProperty(stateIndex)) state[stateIndex] = initialValue;
const value = state[stateIndex];
// Need to create a closure over the current state index...
const closureStateIndex = stateIndex;
const setterFunction = (newValue) => {
state[closureStateIndex] = newValue;
// Re-run the entire function asynchronously:
setTimeout(App);
};
// Increment state index to allow for additional calls to myFunction
stateIndex++;
return [value, setterFunction];
}
const [myValue, updaterFunc] = myFunction('initialValue');
// Call updater only on initial render:
if (myValue === 'initialValue') {
updaterFunc('newValue'); // myValue's new Value should be 'newValue'
}
console.log('Rendering. Current value is:', myValue);
};
App();
这与React的工作方式有点类似.
That's a bit similar to how React does it.
对于具有多个状态变量的示例,并将 myFunction
重命名为 useState
:
For an example with multiple state variables, and renaming myFunction
to useState
:
const state = [];
const App = () => {
let stateIndex = 0;
const useState = (initialValue) => {
if (!state.hasOwnProperty(stateIndex)) state[stateIndex] = initialValue;
const value = state[stateIndex];
const closureStateIndex = stateIndex;
const setterFunction = (newValue) => {
state[closureStateIndex] = newValue;
setTimeout(App);
};
stateIndex++;
return [value, setterFunction];
}
const [name, setName] = useState('bob');
const [age, setAge] = useState(5);
if (age === 5) {
setAge(10);
}
console.log('Rendering. Current name and age is:', name, age);
};
App();
这篇关于如何更新React函数返回的值(useState实现)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!