🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
![](https://img.kancloud.cn/e5/aa/e5aab48f80de442a044b180146589728_885x423.png) ![](https://img.kancloud.cn/b3/af/b3af5e2129662b3f95386d2bcc470e4a_1020x299.png) ![](https://img.kancloud.cn/5b/41/5b413472e02e660e4f0b494655112d82_731x560.png) ~~~ import React from 'react' import PropTypes from 'prop-types' import _ from 'lodash' class Input extends React.Component { constructor(props) { super(props) this.state = { title: '' } } render() { return <div> <input value={this.state.title} onChange={this.onTitleChange}/> <button onClick={this.onSubmit}>提交</button> </div> } onTitleChange = (e) => { this.setState({ title: e.target.value }) } onSubmit = () => { const { submitTitle } = this.props submitTitle(this.state.title) this.setState({ title: '' }) } } // props 类型检查 Input.propTypes = { submitTitle: PropTypes.func.isRequired } class List extends React.Component { constructor(props) { super(props) } render() { const { list } = this.props return <ul>{list.map((item, index) => { return <li key={item.id}> <span>{item.title}</span> </li> })}</ul> } // 增加 shouldComponentUpdate shouldComponentUpdate(nextProps, nextState) { // _.isEqual 做对象或者数组的深度比较(一次性递归到底) if (_.isEqual(nextProps.list, this.props.list)) { // 相等,则不重复渲染 return false } return true // 不相等,则渲染 } } // props 类型检查 List.propTypes = { list: PropTypes.arrayOf(PropTypes.object).isRequired } class TodoListDemo extends React.Component { constructor(props) { super(props) this.state = { list: [ { id: 'id-1', title: '标题1' }, { id: 'id-2', title: '标题2' }, { id: 'id-3', title: '标题3' } ] } } render() { return <div> <Input submitTitle={this.onSubmitTitle}/> <List list={this.state.list}/> </div> } onSubmitTitle = (title) => { // 正确的用法 this.setState({ list: this.state.list.concat({ id: `id-${Date.now()}`, title }) }) // // 为了演示 SCU ,故意写的错误用法 // this.state.list.push({ // id: `id-${Date.now()}`, // title // }) // this.setState({ // list: this.state.list // }) } } export default TodoListDemo ~~~