React的props与state(下)

React的props与state(下)

states 是元件内部状态
State只能在 Class中使用。State的资料结构就是一个物件JavaScript Object。如果一个资料不会用在 render()中显示逻辑,这资料不应该被存在 State。
执行constructor时,他会扫描过一遍有没有state是没有在constructor里,没有的话,他会给undefined。

1.State在Class的constructor() 中用 this.state 来初始化 State 物件。例:this.state={ 变数名称A: 初始化值, 变数名称B: 初始化值,...};
2.在 constructor() 以外的地方,要更新 State 只能透过元件提供的方法 this.setState({ example:15}) 来更新 State。
3.在 constructor() 以外的地方,要将prop的值给state时,要使用this.setState((state, props) => ({ })的方式来给。因为资料可能是非同步更新。
4.setState的第二个参数是个function,当state被设定完之后,就会执行。

Hello.js

import React from "react";class Hello extends React.Component {    constructor(props) {      super(props);      //初始化state的值      this.state = {age:this.props.age,name:this.props.name};      }      play(event){      //元件内部自己维护的 State        this.setState({title: '我的名字是'});        console.log("title",this.state.title);        this.play2()        this.play3();      }      play2(event){        //因为 this.props 和 this.state 为非同步的被更新,它接受一个 function 而不是一个 object。Function 将接收先前的 state 作为第一个参数,并且将更新的 props 作为第二个参数        this.setState((state, props) => ({                  counter: 3 + props.age        }));        console.log('counter',this.state.counter);      }      play3(){          this.setState({abc:'40'});          console.log('abc',this.state.abc);      }              render() {      return (        <div>          <button onClick={this.play.bind(this)}>送出</button>          {console.log('counter',this.state.counter)}          {console.log('abc',this.state.abc)}        </div>      );    }  }  export default Hello;

执行结果:console.log
刚进网页时
//[HMR] Waiting for update signal from WDS...
//Hello.js:37 counter undefined
//Hello.js:37 abc undefined

按下按钮后:值都没有存到state里面。
this.play();
//title undefined
this.play2();
//counter undefined
this.play3();
//abc undefined

一直到render时,state的值才显示出来。
//counter 我的名字是
//counter 321
//abc 40


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章