【问题标题】:Replace Method Not Working as Expected in React Component替换方法在 React 组件中未按预期工作
【发布时间】: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


【解决方案1】:

在 react state 是不可变的,你不能通过简单的赋值来改变状态的值,你需要使用它提供的 setter 函数:

const myComponent = () => {

   const [textVal, setTextVal] = useState("hello there")

   setTextVal(val=> val.replace("hello", "hi"))

   console.log(textVal) 

   return ( ... )

}

【讨论】:

  • 很好,这行得通。想补充一下,我也用了useEffect所以不会重新渲染太多次。
猜你喜欢
  • 2013-03-26
  • 1970-01-01
  • 1970-01-01
  • 2021-05-12
  • 2012-10-31
  • 2011-04-05
  • 2019-04-22
  • 2015-01-28
  • 1970-01-01
相关资源
最近更新 更多