gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 09:12:47 25 4
gpt4 key购买 nike

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

关于reactjs - 如何在 React 中使用 Yield 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63318939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com