-
props 和 state
props 特点是只读,即修改不会让视图同步更新,想要更新必须再次调用 render() 渲染函数
state 特点是可读可写,在使用 this.setState({属性名: 属性值}) 修改时会同步更新视图 -
state 创建和使用
state 必须在类组件的 constructor 内部,通过 this.state = {属性名:属性值} 定义
state 渲染数据:在当前类的 render 函数中,使用 this.state.属性,
state 设置数据:在当前类中,使用 this.setState({属性名: 属性值}) 方法 -
注意事项
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 (
{this.state.state1}
{this.state.propsState}
);
}
}function App() {
return (
);
}export default App;
react state 状态数据
码农NoError2024-08-28 12:12
相关推荐
小徐_23338 小时前
Wot UI 2.2.0 发布:Button 新增 subtle,VideoPreview 预览体验继续增强蜗牛前端3 天前
codex 全流程开发上线的高颜值礼簿小程序爱勇宝6 天前
我想认真做一件小事:让孩子和家长更好地互动唯火锅不可辜负7 天前
避坑指南:iOS 下 scroll-view 嵌套 fixed 布局的“翻车”现场与修复didiplus7 天前
运维人的随身神器:我把25个常用工具塞进了微信小程序一份执念7 天前
uni-app 小程序分包限制处理与主包体积优化实战一份执念7 天前
ECharts 安装与使用完全指南:从全量引入到小程序分包优化skiyee8 天前
🔥UniApp 仅需 5 行代码!实现所有页面中控制应用主题变化Jinkey10 天前
要用户手机号真的是为了打骚扰电话吗?浅谈微信生态会员账号体系与资产合并用户43242810611412 天前
微信小程序从0到1接入微信支付的完整攻略