用visibleText替换基于开始和结束索引的短语。
问题-有多个短语(每个短语每次迭代都会改变).所以transformmedtext的值不会被settransformmedtext钩子刷新
如何在每次迭代中改变settransformmedtext - settransformmedtext之后?
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;
});
这是因为在React中状态更新可能是异步的。