How to update value returned by function React (useState implementation)

前端 未结 1 925
半阙折子戏
半阙折子戏 2021-01-23 07:32

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 calle

相关标签:
1条回答
  • 2021-01-23 08:26

    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();

    That's a bit similar to how React does it.

    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();

    0 讨论(0)
提交回复
热议问题