state和props的区别__react

首先说明: state和props是每个组件都有的
其次: state可变, 但props不可变(这是官网给出的说法)
但实操过程中, state的确可变, 但props也可以变, 是不是fb搞错了? 当然不是!
这里的可变与不可变, 说的是改变后, 是否会重新渲染当前组件. 可变对应的是组件会重新渲染, 不可变(props)是不会渲染的.
至于原因, 则与内部实现机制有关: 每次用
this.setState({test: "test"}) //只能这样更改state
改变state后, 都会触发render函数, 以至于渲染当前组件;
众所周知, react的一个特点就是单向数据流, 也就是说数据只能从父组件向子组件传递, 而这种传递就是依赖于props. 所以当我们改变props时, 无法渲染当前组件, 只能将数据继续向下传递, re-rendering子组件. 所以对于当前组件而言, props是不可变的.
此外, 就字面而言, state是状态, props是属性—即自定义属性, 如下文<ChildComponent boolean />中的”boolean”.

如下所示: state修改后会渲染当前组件

class ParentComponent extends React.Component{
    constructor(props){
        super(props)
        this.state = {boolean: true}
        this.toggleBool = this.toggleBool.bind(this)
    }
    toggleBool(){
        let istrue = this.state.boolean
        this.setState({boolean: !istrue})
    }
    render(){
        return(
            <div>
                <p>{this.state.boolean? "真": "假"}</p>
                <botton onClick={this.toggleBool}>切换状态</button>
            </div>
        )
    }

}
export default ParentComponent

如下所示: props修改后会渲染子组件

class ChildComponent extends React.Component{
    constructor(props){
        super(props)
    }
    render(){
        return(
            <h3>{this.props.boolean? "么么哒": "呵呵哒"}</h3>
        )
    }
}
class ParentComponent extends React.Component{
    constructor(props){
        super(props)
        this.state = {boolean: true}
        this.toggleBool = this.toggleBool.bind(this)
    }
    toggleBool(){
        let istrue = this.state.boolean
        this.setState({boolean: !istrue})
    }
    render(){
        return(
            <div>
                <p>{this.state.boolean? "真": "假"}</p>
                <botton onClick={this.toggleBool}>切换状态</button>
                <ChildComponent boolean={this.state.boolean} />
                /*这个boolean就是props*/
            </div>
        )
    }

}
export default ParentComponent

综上所述, 也就不难理解这两者之间的区别了.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值