如何使用 vanilla JS 复制 useState

2024-04-10

Vanilla JS 中的代码的实现是什么,它允许我们像 React 中的 useState 那样声明和更新状态:

const [x, setX] = useState(12);
setX(14);
console.log(x); // 14

这道题严格来说是get better at JS。天真地说,这样搭配是有意义的:

// Solution 1

function update(value, newValue) {
    value = newValue;
    return value;
}

function state(value) {
    return [ value, update ];
}

let [value, setValue] = state(12)
value = setValue(value, 14)
console.log(value); // 14


// Solution 2

class State {
    constructor(value) {
        this.value = value;
    }
    
    update(newValue) {
        this.value = newValue;
    }
}

const x = new State(12);
x.update(14);
console.log(x.value); // 14

但我不明白数组 [x, setX] 如何有一个回调(setX),当用 const 声明时会影响 x ?我希望这是有道理的。


我也想学习如何实现这一目标。我在这里找到了如何做 https://codesandbox.io/s/ff4rx?file=/src/index.js:673-756。我重构了代码以使用箭头函数 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions相反,这会使代码片段更难阅读和理解。如果是这种情况,请访问上面链接中共享的资源。

这是实现:

const useState = (defaultValue) => {
  // ???? We create a function useState with a default value
  let value = defaultValue;
  // ???? We create a local variable value = defaultValue
  const getValue = () => value
  // ???? We create a function to set the value with parameter newValue
  const setValue = newValue => value = newValue // ???? We change the value for newValue
  return [getValue, setValue]; // ???? We return an array with the value and the function
}

const [counter, setCounter] = useState(0);
// ???? We destructure the array as a return of the useState function into two value

console.log(counter()); // ???? returns 0 which it's the value of counter()

我添加了注释以便于理解。这是没有注释的实现:

const useState = (defaultValue) => {
  let value = defaultValue;
  const getValue = () => value
  const setValue = newValue => value = newValue
  return [getValue, setValue];
}

const [counter, setCounter] = useState(0);

console.log(counter());

为了更好地阅读和理解,我使用了以下代码片段常规功能 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#function_declarations:

function useState(defaultValue) {
  let value = defaultValue

  function getValue() {
    return value
  }

  function setValue(newValue) {
    value = newValue
  }

  return [getValue, setValue];
}

const [counter, setCounter] = useState(0);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 vanilla JS 复制 useState 的相关文章

随机推荐