如何在React(功能组件)中从fetch API数据中检查匹配单词


import React, { useState, useEffect, useRef } from "react";
function App() {
const STARTING_TIME = 10;
const [text, setText] = useState("");
const [timeRemaining, setTimeRemaining] = useState(STARTING_TIME);
const [isTimeRunning, setIsTimeRunning] = useState(false);
const [wordCount, setWordCount] = useState(0);
const textBoxRef = useRef(null);
const [currWordIndex, setCurrWordIndex] = useState(0);
function handleChange(e) {
const { value } = e.target;
setText(value);
}
function calculateWordCount(text) {
const wordsArr = text.trim().split(" ");
return wordsArr.filter((word) => word !== "").length;
}
const [word, setWord] = useState([]);
const fetchData = async () => {
const response = await fetch("https://excuser.herokuapp.com/v1/excuse");
const data = await response.json();
setWord(data);
};
useEffect(() => {
fetchData();
}, []);
function startGame() {
setIsTimeRunning(true);
setTimeRemaining(STARTING_TIME);
setText("");
setCurrWordIndex(0);
textBoxRef.current.disabled = false;
textBoxRef.current.focus();
}
function endGame() {
setIsTimeRunning(false);
setWordCount(calculateWordCount(text));
}
useEffect(() => {
if (isTimeRunning && timeRemaining > 0) {
setTimeout(() => {
setTimeRemaining((time) => time - 1);
}, 1000);
} else if (timeRemaining === 0) {
endGame();
}
}, [timeRemaining, isTimeRunning]);
function handleKeyDown({ keyCode }) {
if (keyCode === 32) {
checkMatch();
setCurrWordIndex(currWordIndex + 1);
}
}
function checkMatch() {
const wordToCompare = word[currWordIndex];
const doesItMatch = wordToCompare === text;
console.log({ doesItMatch });
}
return (
<div>
<h1>How fast do you type?</h1>
<h1>Type the sentence below</h1>
<h3>
{word.map((item) => (
<h3 key={item.id}>{item.excuse}</h3>
))}
</h3>
<textarea
ref={textBoxRef}
onKeyDown={handleKeyDown}
onChange={handleChange}
value={text}
disabled={!isTimeRunning}
/>
<h4>Time remaining: {timeRemaining}</h4>
<button onClick={startGame} disabled={isTimeRunning}>
Start
</button>
<h1>Word count: {wordCount}</h1>
</div>
);
}
export default App;

我无法将提取数据API中的单词与React JS中输入的单词进行匹配。有人知道如何使用功能组件帮助我解决问题吗?因为我找到的大多数答案都是使用类组件的。任何帮助都将不胜感激,谢谢!

我认为您没有检查在checkMatch中比较的值,因为您的状态word当前是对象数组:

word: [
{
id: 306
excuse: "Due to heavy rain, the roads around my area were closed."
category: "college"
}
]

你试着把它和给定字符串的单词数组进行比较。

此外,您的状态text是一个字符串,由用户迄今为止编写的所有文本组成,而不是用户最近编写的单词。

以下功能应适用于您当前的实现:

function checkMatch() {
const words = word[0].excuse.split(' ');
const wordsWritten = text.split(' ');
const wordToCompare = words[currWordIndex];
const doesItMatch = wordToCompare === wordsWritten[currWordIndex];
console.log({ doesItMatch });
}

尽管如此,它并不是非常有效的解决方案(对于较大的文本(,因为在每次单词检查时,您都会将整个文本拆分为单词进行比较。

最新更新