【问题标题】:Why does the component state get updated but the visuals aren't updated?为什么组件状态更新但视觉效果没有更新?
【发布时间】:2024-05-03 13:21:41
【问题描述】:

在调试时,我确认状态正在改变,但单选按钮没有在视觉上更新。奇怪的交互:当我在状态更改后包含要执行的警报时,正确的单选按钮会成为活动选择,但一旦我退出警报,即使状态没有改变,它也会恢复。

  constructor(props) {

        super(props);

        this.state = {
            algorithmType: 'A*'
        }

    }

    radioUpdated = (event) => {

        this.setState({algorithmType: event.currentTarget.value});

    }


    <form>
        <input type='radio' 
        id='PathFinding_RadioButton_Dijkstras'
        name='algorithm' 
        value='Dijkstras'
        checked={this.state.algorithmType == 'Dijkstras' && true}
        onChange={this.radioUpdated}></input>
        <label for="Dijkstras">Dijkstra's</label><br></br>

        <input type='radio'
        id='PathFinding_RadioButton_A*' 
        name='algorithm' 
        value='A*'
        checked={this.state.algorithmType == 'A*'}
        onChange={this.radioUpdated}></input>
        <label for='A*'>A*</label><br></br>

        <input type='radio' 
        id='PathFinding_RadioButton_D*'
        name='algorithm' 
        value='D*' 
        onChange={this.radioUpdated}
        checked={this.state.algorithmType == 'D*'}
        ></input>
        <label for='D*'>D*</label>
     </form>

【问题讨论】:

  • 你的 sn-p 对我有用。组件还有更多内容吗?如果没有,你有哪个版本的reactreact-dom(检查你的package.json)?你用的是哪个浏览器?

标签: reactjs radio-button


【解决方案1】:

我不确定您是否在复制和粘贴代码时出错,您的类组件缺少其渲染功能。

除了您的代码似乎可以正常工作之外,这里是工作示例:

https://codesandbox.io/s/mystifying-gagarin-dh6nz?file=/src/App.js

并且有相同组件的版本,但使用钩子而不是类:

https://codesandbox.io/s/nostalgic-dew-bhy7n?file=/src/App.js

【讨论】:

  • 感谢您的回复!缺少的渲染功能是复制时的错误。由于它显然在简单的上下文中工作,您有什么建议可以研究以找出为什么它在我的项目中不起作用?我发现了一些与我的问题类似的资源,它们指向事件冲突,但尚未找到解决方案。