[英]How to update value returned by function React (useState implementation)
假設我有這樣一個東西,函數返回值和setter函數,我如何正確實現setter函數來更新返回值,每次調用它? (比如 useState 的返回值和 updater 函數)
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 函數導致整個塊再次運行 - 類似於以下內容:
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 的做法。
對於具有多個狀態變量並將myFunction
重命名為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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.