简体   繁体   English

为什么组件 state 更新但视觉效果没有更新?

[英]Why does the component state get updated but the visuals aren't updated?

While debugging I confirmed the state is changing but the radio buttons aren't updating visually.在调试时,我确认 state 正在改变,但单选按钮没有在视觉上更新。 Weird interaction: When I include an alert to be executed after the state has been changed, the correct radio button becomes the active selection but as soon as I exit the alert it reverts back even though the state hadn't changed.奇怪的交互:当我在 state 更改后包含要执行的警报时,正确的单选按钮成为活动选择,但一旦我退出警报,即使 state 没有更改,它也会恢复。

  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>

I'm not sure if you made a mistake in copying and pasting the code, your class component is missing its render function.我不确定您是否在复制和粘贴代码时出错,您的 class 组件缺少其渲染 function。

Apart from that your code seems to work fine, here is working example:除此之外,您的代码似乎工作正常,这里是工作示例:

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

And there is version of the same component, but using hooks instead of a class:并且有相同组件的版本,但使用钩子而不是 class:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM