state和props的区别__react

来源:互联网 发布:测试反应力软件 编辑:程序博客网 时间:2024/05/22 17:09

首先说明: 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

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