【问题标题】:React: Update conditional on state change?React:以状态变化为条件进行更新?
【发布时间】:2022-12-15 16:56:29
【问题描述】:

我认为这将是反应的一个非常基本的功能,但它似乎不会在变量状态更改时更新我的​​代码,例如,如果 isPlaying 更改,图标不会。

例子:

<button id="playButton" onClick={this.onPlayButtonClicked} className="bg-green-500 p-2 px-4 text-white rounded shadow">
{ this.isPlaying ?
    <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 9v6m4-6v6m7-3a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg> :
    <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
}
</button>

【问题讨论】:

  • 你的 isPlaying 状态改变了吗?你能在控制台中检查吗?
  • 是的,它在 onPlayButtonClicked 内部发生了变异,我将其记录到控制台以确保这一点。

标签: reactjs


【解决方案1】:

你能试着给它设置一个键吗,如果可行的话,我会附上一个指向可能解释的链接

<button id="playButton" onClick={this.onPlayButtonClicked} className="bg-green-500 p-2 px-4 text-white rounded shadow">
{ this.isPlaying ?
    <svg key={1} className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 9v6m4-6v6m7-3a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg> :
    <svg key={2} className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
}
</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 2021-11-10
    相关资源
    最近更新 更多