TypeError: null is not an object (evaluating 'variableRegex.exec(foundTranslation)[0]') replaceDynamicString

TypeError: null is not an object (evaluating 'variableRegex.exec(foundTranslation)[0]') replaceDynamicString

我正在摆弄一个 UIkit React 应用程序。我在前端网站上更改了一些文本然后出现此错误。

问题是相关文本没有可用的翻译所以它被列为空吗?

我只是一个业余爱好者,只是在我发现的 github 应用程序上闲逛。

感谢您的帮助。

---错误---

TypeError: null is not an object (evaluating 'variableRegex.exec(foundTranslation)[0]') replaceDynamicString

src/utils/translateTextHelpers.ts:7

   4 | const variableRegex = /%(.*?)%/
   5 | 
   6 | const replaceDynamicString = (foundTranslation: string, fallback: string) => {
>  7 |   const stringToReplace = variableRegex.exec(foundTranslation)[0]
   8 |   // const indexToReplace = foundTranslation.split(' ').indexOf(stringToReplace)
   9 |   const fallbackValueAtIndex = fallback.split(' ')[0]
  10 |   return foundTranslation.replace(stringToReplace, fallbackValueAtIndex)

src/views/Farms/Farms.tsx:107

  104 |     TranslateString(320, 'Stake LP tokens to earn XXXXX')
  105 |   }
  106 | </Heading>
> 107 | <Heading as="h2" color="secondary" mb="50px" style={{ textAlign: 'center' }}>
      | ^  108 |   {TranslateString(10000, 'Please understand the risks before participating.')}
  109 | </Heading>
  110 | <FarmTabButtons stakedOnly={stakedOnly} setStakedOnly={setStakedOnly}/>

(匿名函数) src/contexts/Localisation/languageContext.tsx:68

  65 |   if (translationApiResponse.data.length < 1) {
  66 |     setTranslations(['error'])
  67 |   } else {
> 68 |     setTranslations(translationApiResponse.data)
     | ^  69 |   }
  70 | })
  71 | .then(() => setTranslatedLanguage(selectedLanguage))

来自MDN

The RegExp.prototype.exec() method executes a search for a match in a specified string. Returns a result array, or null.

因此,您需要检查 null。使用 optional chaining and nullish coalescing 运算符的示例:

const stringToReplace = variableRegex.exec(foundTranslation)?.[0] ?? ''