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 (


    <button onClick={this.fnChange1}>点击改变 state</button>
    <button onClick={this.fnChange2}>点击改变 state</button>

    {this.state.state1}


    {this.state.propsState}



    );
    }
    }

    function App() {
    return (


    <Component1 other="props 参数" />

    );
    }

    export default App;

相关推荐
计算机毕设指导61 天前
基于微信小程序的校园食堂点餐系统【源码文末联系】
java·spring boot·微信小程序·小程序·tomcat·maven·intellij-idea
项目題供诗1 天前
微信小程序黑马优购(项目)(八)
微信小程序·小程序
2501_915918411 天前
iOS 项目中证书管理常见的协作问题
android·ios·小程序·https·uni-app·iphone·webview
2501_915918411 天前
提升 iOS 应用安全审核通过率的一种思路,把容易被拒的点先处理
android·安全·ios·小程序·uni-app·iphone·webview
00后程序员张1 天前
APP如何快速上架Apple Store:完整上架流程与常见问题解析
android·小程序·https·uni-app·iphone·webview
Chloe.Zz1 天前
微信小程序接入大模型实战 4:塔罗咨询室(含代码)
语言模型·微信小程序·小程序
2501_916008891 天前
iOS 应用发布流程中常被忽视的关键环节
android·ios·小程序·https·uni-app·iphone·webview
Q_Q5110082851 天前
小程序基于Java Web的健身房管理系统设计和开发
java·前端·小程序
艾上编程1 天前
第四章——桌面小程序场景之使用Tkinter制作文件格式转换器:满足日常格式转换需求
开发语言·小程序
风月歌1 天前
小程序项目之“健康早知道”微信小程序源码(java+小程序+mysql)
java·微信小程序·小程序·毕业设计·源码