【发布时间】:2021-10-18 17:06:02
【问题描述】:
在我的 react 组件中,我使用 replace 方法来替换一个单词,但这似乎不起作用:
const myComponent = () => {
const [textVal, setTextVal] = useState("hello there")
textVal.replace("hello", "hi")
console.log(textVal) // expecting "hi there" but still getting "hello there"
return ( ... )
}
【问题讨论】:
-
两件事:首先,
replace返回一个新字符串,它不会修改旧字符串。其次,如果您希望它在渲染之间保持不变,您需要使用新值调用setTextVal。 -
这能回答你的问题吗? JS replace not working on string
标签: javascript reactjs replace