1.验证Diffing算法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="test"></div>
<script src="../js/17.0.1/react.development.js "></script>
<script src="../js/17.0.1/react-dom.development.js"></script>
<script src="../js/17.0.1/babel.min.js"></script>
<!-- 对标签属性进行限制 -->
<script src="../js/17.0.1/prop-types.js"></script>
<script type="text/babel">
class Time extends React.Component {
state = { date: new Date() }
componentDidMount() {
setInterval(() => {
this.setState({ date: new Date() })
}, 1000)
}
render() {
return (<div>现在时间是{this.state.date.toTimeString()}
<input type="text" /></div>)
}
}
ReactDOM.render(<Time />, document.getElementById('test'))
</script>
</body>
</html>
这段代码是一个使用 React 编写的时钟组件,它会每秒更新一次当前时间并显示在页面上,输入框的数据始终没变,是因为Diffing算法
diffing 算法通过比较虚拟 DOM 树的差异,只更新实际 DOM 中发生变化的部分
2.key的作用
若使用index作为key值:请看代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="test"></div>
<script src="../js/17.0.1/react.development.js "></script>
<script src="../js/17.0.1/react-dom.development.js"></script>
<script src="../js/17.0.1/babel.min.js"></script>
<!-- 对标签属性进行限制 -->
<script src="../js/17.0.1/prop-types.js"></script>
<script type="text/babel">
class Person extends React.Component {
state = {
persons: [
{ id: 1, name: "小李", age: 18 },
{ id: 2, name: "小张", age: 19 }
]
}
add = () => {
const { persons } = this.state
const p = { id: persons.length, name: '小王', age: 20 }
this.setState({ persons: [p, ...persons] })
}
render() {
return (<div>
{this.state.persons.map((item, index) => <li key={index}>{item.name}, {item.age}</li>)}
<button onClick={this.add}>添加小王</button>
</div>)
}
}
ReactDOM.render(<Person />, document.getElementById('test'))
</script>
</body>
</html>