下面是一个简单的例子:
const { Component } = React
const { render } = ReactDOM
const Label = ({ text }) => (
<p>{text}</p>
)
const Clock = ({ date }) => (
<div>{date.toLocaleTimeString()}</div>
)
class App extends Component {
constructor(props) {
super(props)
this.state = {
date: new Date()
}
}
componentDidMount() {
this.interval = setInterval(
() => this.setState({ date: new Date() }),
1000
)
}
componentWillUnmount() {
clearInterval(this.interval)
}
updateTime() {
}
render() {
return (
<div>
<Label text="The current time is:" />
<Clock date={this.state.date} />
</div>
)
}
}
render(<App />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
this.setState({ date: new Date() })
每秒被调用一次,用当前时间更新时钟。据我所知,setState
在 App 上调用 render 方法会导致整个组件重新渲染,包括标签。
有没有办法将日期传递给时钟(导致它被重新渲染)而不重新渲染整个 App 组件?这对性能有多大作用?