state有状态state的组件称作复杂组件,没有状态的组件称为简单组件状态里存储数据,数据的改变驱动页面的展示<scripttype="text/babel">//创建组件classWeatherextendsReact.Component{//构造器调用1次constructor(p
state
- 有状态state的组件称作复杂组件,没有状态的组件称为简单组件
- 状态里存储数据,数据的改变驱动页面的展示
| <script type="text/babel"> |
| |
| |
| class Weather extends React.Component { |
| |
| constructor(props) { |
| super(props); |
| |
| this.state = { isHot: true }; |
| |
| |
| |
| this.changeWeather = this.changeWeather.bind(this); |
| } |
| |
| render() { |
| |
| |
| |
| return <h1 onClick={this.changeWeather} >今天天气{this.state.isHot ? '炎热' : '凉爽'}</h1> |
| } |
| |
| |
| |
| |
| |
| changeWeather() { |
| |
| |
| |
| |
| |
| |
| |
| const isHot = this.state.isHot; |
| this.setState({ isHot: !isHot }); |
| } |
| } |
| |
| |
| const root = ReactDOM.createRoot(document.getElementById('test')); |
| root.render(<Weather />); |
| </script> |
state简写
| class Weather extends React.Component { |
| |
| state = { isHot: true }; |
| |
| render() { |
| return <h1 onClick={this.changeWeather} >今天天气{this.state.isHot ? '炎热' : '凉爽'}</h1> |
| } |
| |
| |
| |
| changeWeather = () => { |
| const isHot = this.state.isHot; |
| this.setState({ isHot: !isHot }); |
| } |
| } |
| |
| const root = ReactDOM.createRoot(document.getElementById('test')); |
| root.render(<Weather />); |
| </script> |
setState的更新可能是异步的
出于性能考虑,React 可能会把多个 setState()
调用合并成一个调用。
要解决这个问题,可以让 setState()
接收一个函数而不是一个对象。这个函数用上一个 state 作为第一个参数,将此次更新被应用时的 props 做为第二个参数:
| |
| this.setState((state, props) => ({ |
| counter: state.counter + props.increment |
| })); |
| |
| this.setState(function(state, props) { |
| return { |
| counter: state.counter + props.increment |
| }; |
| }); |