reactjs - 添加额外检查时 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 是“”,这意味着如果新文本为空,则不要更新
当我使用这段代码单击保存按钮时。什么都没有发生,它不会像以前那样用以前的数据呈现笔记。这里有什么问题?
解决方案
推荐阅读
- python - 使用python从Excel表格中提取图像
- vb.net - 使用 vb.net 使用公钥进行 pgp 加密
- angular - 如何防止 Angular 应用程序在 Index.html 中加载
- android - Parcelable Map的正确方法?
- joomla - 如何在 Joomla 中为插件添加参数?
- php - 根据列值动态选择列
- mongodb - StreamSets 获取 MongoDB 字段
- git - 如何从另一台计算机更新现有的 github 存储库?
- sql - 将表和数据库服务器传递给存储过程
- spring - 将 Mapstruct 上下文包含到内部映射器中