如何在 React 中使用 Yield 关键字?

How to use the Yield keyword in React?

我在 React 中使用 yield 关键字时遇到一些奇怪的行为。

我希望发生的是呈现一个按钮和计数。每次按下按钮时,计数都会设置为下一个屈服值,并显示在屏幕上。我希望记录以下内容:

Creating someProcess
0
1
2
3
4
5 
...

实际发生的是计数值保持在 0 或 1。实际记录的内容如下:

Creating someProcess
0
1
Creating someProcess
0
Creating someProcess
0
Creating someProcess
0
1
Creating someProcess
0
...

所以据我所知,似乎所有代码都被重新执行,这导致生成器函数被重新初始化。

如何防止这种行为?

MyComponent.js

const MyComponent.js = () => {

    // A generator function that yields the numbers 1 through 10
    function* someProcess(someValue) {
        console.log("Creating someProcess");
        for (let i = 0; i < someValue; i += 1) {
            yield i;
        }
    }

    // Getting an instance of the generator
    const process = someProcess(10);

    // Some state for the count
    const [count, setCount] = useState(0);

    // onClick handler to get the next yield value and set the count state to that value
    const getNextYieldValue = () => {
        const nextValue = process.next().value;
        console.log(nextValue);
        setCount(nextValue);
    };

    return (
        <div>
            <button onClick={getNextYieldValue} type="button">Get Next Value</button>
            <Child count={count} />
        </div>
    );
};

将生成器放在功能组件之外。每次组件渲染时,都会调用该函数,该函数会从头开始重新创建生成器,因此当前状态会丢失。

// A generator function that yields the numbers 1 through 10
function* someProcess(someValue) {
  console.log("Creating someProcess");
  for (let i = 0; i < someValue; i += 1) {
    yield i;
  }
}

// Getting an instance of the generator
const process = someProcess(10);

MyComponent.js = () => {
    // Some state for the count
    const [count, setCount] = useState(0);

    // onClick handler to get the next yield value and set the count state to that value
    const getNextYieldValue = () => {
        const nextValue = process.next().value;
        console.log(nextValue);
        setCount(nextValue);
    };

    return (
        <div>
            <button onClick={getNextYieldValue} type="button">Get Next Value</button>
            <Child count={count} />
        </div>
    );
};