React学习笔记-03 state

时间:2021-11-19 11:55:54

每一个组件都有状态,比如一个开关,开 和 关,都是一种state.那么react是怎么管理它的state的?

React 把用户界面当做状态机,可以轻松的让用户界面和数据保持一致。用户只需要更新组件的state就可以重新渲染用户界面,不用操作DOM。

state:

  1.可以通过getInitialState方法初始化state

    getInitialState:function(){

      return {

        open :true

      }

    }

  2.通过setState("open",false)去改变state状态,然后重新渲染页面。那有人会说,为啥一定要用setState,不能通过this.state.open = false去改变状态吗?这两种有啥区别呢?

  使用setState去改变状态时,React会主动去渲染VDOM结构,但是使用this.state.open去设置,不会主动去渲染VDOM,需要手动去调用forceUpdate()去强制更新。

state应该保存什么?

state不要保存props的计算值,也不要保存render(0不使用的状态。

eg:

class Component extends React.Component{
        constructor(props){
          super(props);
          this.state = {message:props.message}
        },
        render:function(){
          return (<div>{this.state.message}</div>);
        }
      }

  在这个例子中,state只在第一次创建组件的时候才被赋值,当props变化后,state值不会变,因此界面不会更新。因此不得不在componentWillReceiveProps()中更新state,,导致真实的数据源重复

正确实现:

class Component extends React.Component{
        constructor(props){
          super(props);
        },
        render:function(){
          return (<div>{this.props.message}</div>);
        }
      }

  //不要在state中存储props的计算值

eg:

 class Component extends React.Component{
        constructor(props){
          super(props);
          this.state = {
            fullname:'${props.name}${props.lastName}'
          };
        },
        render:function(){
          return (<div>{this.state.fullname}</div>);
        }
      }

  更好的实现:

class Component extends React.Component{
        constructor(props){
          super(props);
        },
        render:function(){
        const {name,funllname}=this.props;
          return (<div>{'${name}${fullname}'}</div>);
        }
      }

  目前还没有学习redux,对state的理解还不够深入,先写点吧。。。。后续更新