首页 > 解决方案 > 添加额外检查时 shouldComponentUpdate 不起作用?

问题描述

我是反应的初学者,我试图制作一个备忘录应用程序,最后我应用了奇怪的 shouldComponentUpdate 方法来检查以前的道具和状态的值是否不同以及备忘录是否未定义为空.

一切正常,但是当我补充说,如果笔记不为空,则保存 btn 停止工作!

这是我的笔记组件

class Note extends React.Component {
    constructor(props){
        super(props)
        this.edit = this.edit.bind(this)
        this.remove = this.remove.bind(this)
        this.save   = this.save.bind(this)
        this.randomBetween = this.randomBetween.bind(this)
        this.state    = {editing:false}

    }


    shouldComponentUpdate (newProps,newState){
        return (newProps.children !== this.props.children || newState !== this.state)

    }

    edit(e){
        this.setState({editing:true})
    }
    remove(e){
        e.preventDefault()
        this.props.remove(this.props.id)
    }

    save(e){
        e.preventDefault()
        var newText = this.NoteInput.value
        this.props.update(this.props.id,newText)
        this.setState({editing:false})

    }

    formDisplay(){
        return (
            <div className='note' style={this.style}>
                <form>
                <input type="text" className="note-input" ref={input => this.NoteInput = input} defaultValue = {this.props.children}></input>
                <button onClick={this.save}>save</button>
                </form> 
            </div>
        )
    }
    noteDisplay(){
        return (
            <div className="note" ref = {note => this.note = note} style={this.style}>
                <p>{this.props.children}</p>
                <span>
                    <button className="edit" onClick={this.edit}>edit</button>
                    <button className="remove" onClick={this.remove}>remove</button>
                </span>     
            </div>
        )
    }

    render() {
        return this.state.editing ? this.formDisplay() : this.noteDisplay()
    }


}

所有这些代码都可以正常工作,但是当将此代码添加到“shouldComponentUpdate”时它不起作用

shouldComponentUpdate (newProps,newState){
        return ((newProps.children !== this.props.children || newState !== this.state) && newProps.children !== "")

    }

这基本上添加了一个额外的检查,如果 newprop.children 是“”,这意味着如果新文本为空,则不要更新

当我使用这段代码单击保存按钮时。什么都没有发生,它不会像以前那样用以前的数据呈现笔记。这里有什么问题?

标签: reactjsreact-domreact-component

解决方案


推荐阅读