欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 焦点 > react state 状态数据

react state 状态数据

2025/9/27 12:51:52 来源:https://blog.csdn.net/zhangzhaoyuxunlei/article/details/141587184  浏览:    关键词:react state 状态数据
  1. props 和 state
    props 特点是只读,即修改不会让视图同步更新,想要更新必须再次调用 render() 渲染函数
    state 特点是可读可写,在使用 this.setState({属性名: 属性值}) 修改时会同步更新视图
  2. state 创建和使用
    state 必须在类组件的 constructor 内部,通过 this.state = {属性名:属性值} 定义
    state 渲染数据:在当前类的 render 函数中,使用 this.state.属性,
    state 设置数据:在当前类中,使用 this.setState({属性名: 属性值}) 方法
  3. 注意事项
    this.setState() 是异步的,如果需要在数据改变后执行,可以在 this.setState() 的回调函数中执行

import React from "react";
class Component1 extends React.Component {constructor(props) {super(props);this.state = {state1: "状态1",propsState: this.props.other,};}fnChange1 = () => {this.setState({ state1: "变化后的状态 state1" }, () => {console.log(this.state.state1);});console.log(this.state.state1);};fnChange2 = () => {this.setState({ propsState: "变化后的状态 propsState" }, () => {console.log(this.state.propsState);});console.log(this.state.propsState);};render() {return (<div><button onClick={this.fnChange1}>点击改变 state</button><button onClick={this.fnChange2}>点击改变 state</button><h1>{this.state.state1}</h1><h1>{this.state.propsState}</h1></div>);}
}function App() {return (<div><Component1 other="props 参数" /></div>);
}export default App;



 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词