多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] ## 概述 State 与 props 类似,但是 state 是私有的,并且完全受控于当前组件。 ## state ``` //赋值 this.state={date:new Date()} //更新 this.setState({date:new Date()}); ``` ### State 的更新可能是异步的 ``` //error this.setState((state, props) => ({ counter: state.counter + props.increment })); // Correct this.setState((state, props) => ({ counter: state.counter + props.increment })); ``` ## 例子 ### 一个定时器demo ``` class App extends Component { constructor(props) { super(props); // this.state={date:new Date()} this.state={date:new Date()} } //组件被渲染到DOM后执行 componentDidMount() { this.timeId = setInterval(()=>this.tick(),1000); } componentWillUnmount() { clearInterval(this.timeId); } tick() { this.setState({date:new Date()}); } render() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> <p>time {this.state.date.toLocaleTimeString()}</p> </header> </div> ); } } ```