ReactDOM.render
React元素是不可变的,一旦创建了就不可以更新,我们通过ReactDOM.render创建组件,那我们也可以通过重新调用该方法来实现UI更新的效果
function Clock(props) {return (<div><h1>Hello, world!</h1><h2>It is {props.date.toLocaleTimeString()}.</h2></div>);}function tick() {ReactDOM.render(<Clock date={new Date()} />,document.getElementById('root'));}setInterval(tick, 1000);
class组件也是如此,只不过是把函数组件修改成class的写法了,注意这个地方,props修改为this.props,因为class组件继承于React.compnent,所以class组件有生命周期函数,当然,后期,函数式组件也具有了生命周期,供组件使用state
class Clock extends React.Component {render() {return (<div><h1>Hello, world!</h1><h2>It is {this.props.date.toLocaleTimeString()}.</h2></div>);}}function tick() {ReactDOM.render(<Clock date={new Date()} />,document.getElementById('root'));}setInterval(tick, 1000);
state更新UI
通过生命周期来设置定时器,然后通过setState来动态改变UI里面的值
import React from 'react';class App extends React.Component{constructor(props) {super(props)this.state = {date: new Date()}}componentDidMount() {this.timer = setInterval(() => {this.tick()}, 1000)}tick() {this.setState({date: new Date()})}componentWillUnmount() {clearInterval(this.timer)}render() {return (<div><h1>hello world</h1><h2>it is now:{this.state.date.toLocaleTimeString()}</h2></div>)}}export default App;
注意
不要直接修改state
// 错误this.state.date = 'new Value'// 正确this.setState({date: 'new Value'})
state更新可能是异步的(因为出于性能考虑,React 可能会把多个 setState() 调用合并成一个调用)
// Wrongthis.setState({counter: this.state.counter + this.props.increment,});// Correct---箭头函数this.setState((state, props) => ({counter: state.counter + props.increment}));// Correctthis.setState(function(state, props) {return {counter: state.counter + props.increment};});
state更新可以合并
