如何在React中使用Yield关键字



在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>
);
};

最新更新