Home  >  Q&A  >  body text

javascript - reactjs 视图更新失败

react IE情况下选中要选择的项后 数据更新了但是视图没更新
$('.textBut').on('click',function(){

            if($(this).attr('level')>=1){
                console.log($(this).text());
                that.setState({
                    accName:$(this).text(),
                    accCode:$(this).attr('newcode'),
                    item_id:$(this).attr('item_id')
                },function(){
                    $('#biubibiu').html('');
                })
            }
        })`请输入代码`

<input type="text" value={this.state.accName} readOnly={true} onClick={that.treeSle.bind(that)} className="form-control" />请输入代码
PHP中文网PHP中文网2719 days ago570

reply all(4)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-11 11:40:56

    react应该修改state状态来更新组件,而不是通过jquery这种直接操作dom的方式
    比方

    class Example extends Component{
        constructor(props){
            super(props)
            this.state={
                inputVaule:''
            }
        }
    
        render(){
            return(
                <p>
                    <input value={this.state.inputVaule} onChange={()=>this.recordInputChange()} ref="inputTxt"/>
                    <button onClick={()=>this.example()} />
                </p>
            )
        }
        recordInputChange(){
            this.setState({
                inputValue:this.refs.inputTxt.value
            })
        }
    
        function example(){
          console.log('the input value is',this.state.inputValue)
        }
    }

    reply
    0
  • 高洛峰

    高洛峰2017-04-11 11:40:56

    数据驱动视图是众多mvvm的核心概念,但对于众多习惯了jquery等开发方式的前端来讲,会有点小不适应。总是手痒,想去直接操作一下 dom。坦白讲,确实有些场景直接操作dom要来的方便点,但是既然用了react,就竟可能按照它的世界观来,不然会很不好维护。

    reply
    0
  • PHP中文网

    PHP中文网2017-04-11 11:40:56

    因为没看到题主全部的代码,我只能提供一点意见而已。

    this.setState有可能是异步执行的,不一定你这一会数据已更动,就会马上作视图(真实DOM上)的更动。
    尤其是像这种React控不了的直接抓DOM上值的代码。

    请看我写的文章: 为何说setState方法是异步的?

    reply
    0
  • PHP中文网

    PHP中文网2017-04-11 11:40:56

    • this.setState来更改数据 或者

    • 如果真的非得操作dom 在真正的dom渲染出来之后 也就是在componentDidMount在这个方法中操作dom

    reply
    0
  • Cancelreply