【React整理系列】Props和State

    技术2022-07-17  77

    【React整理系列】Props和State

    props作为对象,将 JSX 所接收的属性(attributes)以及子组件(children)转换为单个对象传递给组件。组件无论是使用函数声明还是通过 class 声明,都决不能修改自身的 props。

    ​ 文档声明:

    React 非常灵活,但它也有一个严格的规则:

    所有 React 组件都必须像纯函数一样保护它们的 props 不被更改。

    如果需要改变的变量,则使用state:

    ​ state 是私有的,并且完全受控于当前组件

    组件名称必须以大写字母开头。

    一个标准的函数式组件(与hooks结合,已经成为主流):

    function Welcome(props) { return <h1>Hello, {props.name}</h1>; } 一个标准的类组件(要注意,继承的是React.Component,另外类组件已经逐步废弃) : class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } }

    React 元素也可以是用户自定义的组件,也就是可以把组件赋值给变量:

    const element = <Welcome name="Sara" />; function Welcome(props) { return <h1>Hello, {props.name}</h1>; } const element = <Welcome name="Sara" />;ReactDOM.render( element, document.getElementById('root') );

    尽管 this.props 和 this.state 是 React 本身设置的,且都拥有特殊的含义,但是其实你可以向 class 中随意添加不参与数据流(比如计时器 ID)的额外字段。

    关于state:

    不要直接修改state,而是应该通过setState进行修改。 // Wrong this.state.comment = 'Hello'; // Correct this.setState({comment: 'Hello'});

    ​ 而构造函数是唯一可以给 this.state 赋值的地方:

    State 的更新可能是异步的 :

    官网文档中这样描述:

    出于性能考虑,React 可能会把多个 setState() 调用合并成一个调用。

    因为 this.props 和 this.state 可能会异步更新,所以你不要依赖他们的值来更新下一个状态。

    例如,此代码可能会无法更新计数器:》要解决这个问题,可以让 setState() 接收一个函数而不是一个对象。这个函数用上一个 state 作为第一个参数,将此次更新被应用时的 props 做为第二个参数:

    要解决这个问题,可以让 setState() 接收一个函数而不是一个对象。这个函数用上一个 state 作为第一个参数,将此次更新被应用时的 props 做为第二个参数:

    // Wrong this.setState({ counter: this.state.counter + this.props.increment, }); // Correct this.setState((state, props) => ({ counter: state.counter + props.increment })); //上面使用了箭头函数,不过使用普通的函数也同样可以: // Correct this.setState(function(state, props) { return { counter: state.counter + props.increment }; });

    乍看上去挺迷茫的,这里暂时理解成,如果更新state需要依赖于props或者原来的state的话,那么必须以传入函数的形式进行更新。

    State 的更新会被合并

    当你调用 setState() 的时候,React 会把你提供的对象合并到 当前的 state。

    也就是可以单独更新某个值

    React单向数据流
    Processed: 0.011, SQL: 9