我正在尝试了解 useState 和 useEffect,但我想我还没来得及走路就已经开始跑步了。
我有一组单词:
const words = ["There", "Their", "They're", "Were"];
我想显示数组中的第一个词,当我点击“下一个词”时它会切换到下一个词,点击“上一个词”会跳到上一个词。
使用 useState 足够简单了吧?
这是我的代码:
import { useState, useEffect } from 'react';
const Array = () => {
const words = ["There", "Their", "They're", "Were"];
const [count, setCount] = useState(0);
const [word, setWord] = useState(words[0]);
return (
<div>
<button onClick={prevWord}>Prev Word</button>
<span>{words[count]} </span>
<button onClick={nextWord}>Next Word</button>
</div>
);
}
export default Array;
第一期:
当我点击“下一个词”或“上一个词”时,它会点击整个数组,不幸的是它一直在前进。如果用户点击“下一个词”,例如 15 次,他必须点击 12 次“上一个词”才能再次看到一个词,我不喜欢这一点。修复方法是什么?
我的第二个问题
然后我想更进一步。当我单击下一个字母时,我希望它显示第一个字母,每次单击“下一步”时都会添加下一个字母。
我目前在控制台中显示了字母,但我不知道如何显示它们我想要的?
这是我所拥有的一切的完整代码:
import { useState, useEffect } from 'react';
const Array = () => {
const words = ["There", "Their", "They're", "Were"];
const [count, setCount] = useState(0);
const [countLetter, setCountLetter] = useState(0);
const [word, setWord] = useState(words[0]);
const [letter, setLetter] = useState(word[0]);
const nextWord = (() => {
setCount(prevCount => prevCount + 1)
console.log(words[count]);
})
const prevWord = (() => {
setCount(prevCount => prevCount - 1)
console.log(words[count]);
})
const nextLetter = (() => {
setCountLetter(prevcountLetter => prevcountLetter + 1)
console.log(word[countLetter]);
})
const prevLetter = (() => {
setCountLetter(prevcountLetter => prevcountLetter - 1)
console.log(word[countLetter]);
})
// console.log(word[count]); // spells the word
// console.log(word[count]); // spells the word
return (
<div>
<button onClick={prevLetter}>Prev Letter</button>
<button onClick={prevWord}>Prev Word</button>
<span>{words[count]} </span>
<button onClick={nextWord}>Next Word</button>
<button onClick={nextLetter}>Next Letter</button>
</div>
);
}
export default Array;
感谢任何帮助。
答案 0 :(得分:0)
counts
是否在 0 和 words.length
之内。 const nextWord = (() => {
if (count < words.length) {
setCount(prevCount => prevCount + 1);
console.log(words[count]);
}
})
const prevWord = (() => {
if (count > 0) {
setCount(prevCount => prevCount - 1)
console.log(words[count]);
}
})
letter
。或者至少检查新单词的长度是否相等或更大,以避免超出单词的边界。在调用 setCountLetter
之前还要检查当前的单词边界。 const nextWord = (() => {
if (count < words.length) {
setCount(prevCount => prevCount + 1);
setCountLetter(0);
console.log(words[count]);
}
})
const prevWord = (() => {
if (count > 0) {
setCount(prevCount => prevCount - 1);
setCountLetter(0);
console.log(words[count]);
}
})
const nextLetter = (() => {
if (letter < words[count].length) {
setCountLetter(prevcountLetter => prevcountLetter + 1)
console.log(word[countLetter]);
}
})
const prevLetter = (() => {
if (letter > 0) {
setCountLetter(prevcountLetter => prevcountLetter - 1)
console.log(word[countLetter]);
}
})