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

时间:2021-05-03 13:50:35

标签: javascript html reactjs frontend getuikit

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

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

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

感谢您的帮助。

---错误---

<块引用>

TypeError: null is not an object (evaluating 'variableRegex.exec(foundTranslation)[0]') 替换动态字符串

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))

1 个答案:

答案 0 :(得分:0)

来自MDN

<块引用>

RegExp.prototype.exec() 方法执行对指定字符串中的匹配项的搜索。返回结果数组,或 null

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

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