4. react 组件中的 state
1. 组件中的 props 和 state :
1. props 是由父组件(父类)传入的, state 是完全受组件自己控制的
通过一个案例来熟悉 state , 两种不同的方式封装组件,一种使用 props 传递参数,一种使用 state 做到解耦的方式封装
案例一: props 传递参数方式:
function Clock (props) { return ( <div> <h1>Hello, world!</h1> <h2>It is {props.date.toLocaleTimeString()}</h2> </div> ); } function tick () { ReactDOM.render( <Clock date= {new Date()}/>, document.getElementById('root') ) } setInterval(tick, 1000);
案例二: state 改造 Clock 组件
// state 改造 Clock 组件 class Clock extends React.Component { constructor (props) { super(props) this.state = { date: new Date() } } // 生命周期 componentDidMount () { this.timer = setInterval(()=> this.tick(), 1000) } componentWillUnmount () { clearInterval(this.timer) } render () { return ( <div> <h1>Hello, world!</h1> <h2>It is {this.state.date.toLocaleTimeString()}</h2> </div> ) } tick() { this.setState({ date: new Date() }); } }
2. state 属性的修改:
1. state 的数据是局部的或是封装的,除了拥有并设置了它的组件,其他组件都无法访问
2. state 中的数据只能向下流动,且每个组件中的state是独立的
3. this.state.attr = attrValue 这种方式不能触发重新渲染组件。而是使用 setState(),this.setState({ attr: newValue })
4. state 的更新是异步的,不能把 this.state 或者 this.props 的上一个状态直接作为值更新 state 的值,那么如何更新呢?
那么如何更新呢? 我们可以在 this.setState() 中传入函数来修改,例如:
// Wrong this.setState({ counter: this.state.counter + this.props.increment, });
// Correct this.setState((state, props) => ({ counter: state.counter + props.increment }));
6. state 中的属性可以作为 props 的属性向下传递。案例:
// 在 parent.js 中 父组件中 import React from 'react'; import Children from './children' class Parent extends React.Component { constructor (props) { super(props) this.state = { comment: "我是父组件中的state数据" } } render () { return ( <div> 我是父组件 <Children comment={this.state.comment} /> </div> ) } } export default Parent
// 在 children.js 中 子组件中 import React from 'react'; class Children extends React.Component { constructor (props) { super(props) this.state = { } } render () { return ( <div> 我是子组件 <div> 我是父组件state传递过来的数据: {this.props.comment} </div> </div> ) } } export default Children
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)