【问题标题】:Weird behavior using a generator function with React使用带有 React 的生成器函数的奇怪行为
【发布时间】:2023-03-23 19:50:02
【问题描述】:

下面是我的精简组件。它有一个生成器函数,应该循环遍历值。

const App = () => {
  const [state, setState] = useState("1")

  function* stateSwitch () {
    while (true){
      yield "2"
      yield "3"
      yield "1"
    }
  }

  const stateSwitcher = stateSwitch()

  const handleClick = event => {
    event.preventDefault()
    console.log(stateSwitcher.next().value)
    setState(stateSwitcher.next().value)
  }

  return (
    <div className="App">
      <button onClick = {handleClick}>{state}</button>
    </div>
  );
}

这种行为很奇怪。获取按钮上显示的新值需要单击一次,然后单击两次,然后再次单击一次,以此类推。有时状态为“3”,但只有“1”和“2”被记录。

我不明白这是怎么发生的,我想这与我还不知道的 React 组件生命周期有关。有人可以帮我吗?

【问题讨论】:

    标签: javascript reactjs generator


    【解决方案1】:

    console.log(stateSwitcher.next().value)setState(stateSwitcher.next().value) 中的一个正在消耗其中一个收益。

    每个渲染周期都会重新定义生成器。

    试试吧

    function* stateSwitch() {
      while (true) {
        yield "2";
        yield "3";
        yield "1";
      }
    }
    
    const stateSwitcher = stateSwitch();
    
    export default function App() {
      const [state, setState] = useState("1");
    
      const handleClick = (event) => {
        event.preventDefault();
        const value = stateSwitcher.next().value;
        console.log(value);
        setState(value);
      };
    
      return (
        <div className="App">
          <button onClick={handleClick}>{state}</button>
        </div>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-07
      • 2016-03-19
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      • 1970-01-01
      • 2017-11-18
      • 2014-01-28
      • 1970-01-01
      相关资源
      最近更新 更多