【发布时间】:2021-11-24 00:09:54
【问题描述】:
我有一个字符串数组要显示const array = ["one", "two", "three"]; 。
UI 最初显示数组中的第一项,即"one"。从那里我有一个按钮right,点击它会显示下一个项目或字符串two,然后是three,在three之后它应该回到one并从那里重新开始。
我还有一个left按钮,点击时显示上一个项目或字符串,如果当前字符串是two,前一个字符串是one,然后在one之后它从three开始并走向后。
我正在使用生成器来执行此操作。这是我的尝试
function* stepGen(steps) {
let index = 0;
while (true) {
const direction = yield steps[index];
index = (index + (direction === "forward" ? 1 : -1)) % steps.length;
}
}
const array = ["one", "two", "three"];
let gen = stepGen(array);
const getNext = () => gen.next("forward").value;
const getPrev = () => gen.next("backward").value;
export default function App() {
const [current, setCurrent] = useState(() => getNext());
const onRight = () => {
const next = getNext();
setCurrent(next);
};
const onLeft = () => {
const prev = getPrev();
setCurrent(prev);
};
return (
<div className="App">
<h1>{current}</h1>
<button onClick={onLeft}>left</button>
<button onClick={onRight}>right</button>
</div>
);
}
这是一个你可以玩的现场演示 https://codesandbox.io/s/cyclethrough1-deh8p?file=/src/App.js
显然当前的行为是错误的。有多个问题我不知道原因和解决方法:
-
用户界面以
two开头,而不是one。我想这与我如何启动我的状态有关current
const [current, setCurrent] = useState(() => getNext());
我认为() => getNext() 只会在组件首次挂载时被调用一次,所以current 从一开始就应该是one。
我试图用
启动状态const [current, setCurrent] = useState(array[0]);
它确实从数组中的第一项开始,即one,但您必须单击两次right 按钮才能转到two。这是此变体的现场演示https://codesandbox.io/s/cyclethrough2-5gews?file=/src/App.js
-
left按钮,应该向后走循环不起作用。它完全坏掉了。right按钮虽然有效。不知道为什么。
【问题讨论】:
标签: javascript reactjs ecmascript-6 es6-generator