在 Hook 循环中刷新状态

Have refreshed state in Hook in loop

根据开始和结束索引将短语替换为可见文本。

问题 - 有多个短语(每个短语每次迭代都在变化) . 所以 transformedText 的值没有被 setTransformedText hook 刷新。

如何在每次迭代中更改 transformedText - 在 setTransformedText 之后?

for(const i in phrasesByCategory){

  const startIndex = phrasesByCategory[i].start_char;
  const endIndex = phrasesByCategory[i].end_char;
  const hiddenText = transformedText.substring(startIndex, endIndex);
  const visibleText = text.substring(startIndex, endIndex)

  const replacedPhrase  = replaceAt(transformedText, hiddenText, visibleText, startIndex, endIndex)

  setTransformedText(replacedPhrase)
}

钩子是字符串:

  const [transformedText, setTransformedText] = useState("")

它取代了第一次迭代:

  const makeVisible = (phrasesByCategory) => {

    let currentText = transformedText
    setTransformedText((transformedText)=> {
      for(const i in phrasesByCategory){
        const startIndex = phrasesByCategory[i].start_char;
        const endIndex = phrasesByCategory[i].end_char;
        const hiddenText = transformedText.substring(startIndex, endIndex);
        const visibleText = text.substring(startIndex, endIndex);
        const replacedPhrase  = replaceAt(transformedText, hiddenText, visibleText, startIndex, endIndex)
        currentText = replacedPhrase
      }
      return currentText;
  })
}

编辑当前解决方案 - 最终匿名化和非匿名化该短语:

  const anonymyseByCategory = (phrasesByCategory, visible) => {
    const textArray = [transformedText];
    for (const i in phrasesByCategory) {
      const startIndex = phrasesByCategory[i].start_char;
      const endIndex = phrasesByCategory[i].end_char;
      let hiddenText = visible
        ? textArray[i].substring(startIndex, endIndex)
        : textArray[i].substring(startIndex, endIndex).replace(textArray[i].substring(startIndex, endIndex), 'X'.repeat(textArray[i].substring(startIndex, endIndex).length))
      const visibleText = text.substring(startIndex, endIndex);
      const sentenceWithReplacedPhrases = visible
        ? replaceAt(textArray[i], hiddenText, visibleText, startIndex, endIndex)
        : replaceAt(textArray[i], visibleText, hiddenText, startIndex, endIndex)
      textArray.push(sentenceWithReplacedPhrases)
      setTransformedText(sentenceWithReplacedPhrases);
    }
  }

我猜你有类似的东西:

let [transformedText, setTransformedText] = useState('Hello World');

由于您正在使用状态 属性 (transformedText) 的先前值来更新它,因此您必须调用您的状态 属性 setter ( setTransformedText) 回调。

setTransformedText((transformedText)=> {
    var hiddenText = ...;
    var visibleText = ...;
    var replacedPhrase = replaceAt(...);
    return replacedPhrase;
});

这是因为状态更新 may be asynchronous in React