You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React TypeScript中如何在Promise中使用array.includes?及.includes()方法异常问题排查

Troubleshooting .includes() Always Returning False in React + TypeScript

Let's break down what's going wrong here and fix it step by step:

Core Issue: Unnecessary Async Wrapping + Potential Word List Loading/Formatting Problems

First off: JavaScript's Array.includes() is a synchronous method — wrapping it in a Promise doesn't solve any real problem here, and it might be obscuring the actual issue. The main reasons your check is always returning false are almost certainly one of these:

  1. Your allWords array isn't fully loaded or initialized when you call validateGuess
  2. The word you're generating doesn't match the format of entries in allWords (e.g., case mismatch, extra whitespace)

Step 1: Simplify Your Validation Function

Let's strip out the unnecessary async code to make debugging easier. Since includes() is synchronous, we don't need promises here:

// helpers.ts
export function validateGuess(guess: GuessCharacter[]): boolean {
  // Use map + join for cleaner string construction
  const word = guess.map(character => character.value).join('');
  // Optional: Normalize case if your word list uses lowercase exclusively
  const normalizedWord = word.toLowerCase();
  return allWords.includes(normalizedWord);
}

Step 2: Verify allWords is Properly Loaded

If allWords is a static array imported directly (e.g., import allWords from './word-list.json'), check that the import is working by logging its length before calling validation:

function handleEnterPress() {
  console.log('allWords length:', allWords.length); // Should show 12000
  const guess = gameState.guesses[gameState.guessCount];
  const word = guess.map(char => char.value).join('');
  console.log('Generated word:', word); // Check if this matches expected format
  
  if (validateGuess(guess)) {
    dispatch(ActionKind.Enter);
  } else {
    console.log('Not in word list');
  }
}

If allWords is loaded asynchronously (e.g., from an API or dynamic file), you need to track its loading state in your React component:

// In your component
import { useState, useEffect } from 'react';

const [allWords, setAllWords] = useState<string[]>([]);
const [isWordListLoaded, setIsWordListLoaded] = useState(false);

useEffect(() => {
  // Replace with your actual async loading logic
  fetch('/path-to-your-word-list.json')
    .then(res => res.json())
    .then(wordList => {
      setAllWords(wordList);
      setIsWordListLoaded(true);
    })
    .catch(err => console.error('Failed to load word list:', err));
}, []);

function handleEnterPress() {
  if (!isWordListLoaded) {
    console.log('Word list is still loading — please wait!');
    return;
  }

  const isValid = validateGuess(gameState.guesses[gameState.guessCount]);
  if (isValid) {
    dispatch(ActionKind.Enter);
  } else {
    console.log('Not in word list');
  }
}

Step 3: Check for Format Mismatches

It's common for word lists to use all lowercase, but user input might include uppercase letters. Always normalize both the generated word and the list entries to the same case (like we did in the simplified validateGuess function above).

Also, double-check that your GuessCharacter objects' value property doesn't include extra spaces, special characters, or typos that would make the generated word not match entries in allWords.


Why Your CodeSandbox Worked But React App Didn't

In CodeSandbox, your allWords array is probably loaded synchronously (e.g., as a static import) and immediately available. In your full React app, there's a good chance the word list is being loaded asynchronously, and you're trying to validate guesses before the list is ready.

内容的提问来源于stack exchange,提问作者Mac Bubb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 17:09:08