简述
this.setState 方法是React组件类(React.Component 的子类)的一个内置方法。当你在创建一个React组件类时,你继承自 React.Component,因此你的组件类会自动获得this.setState 方法。 this.setState 用于更新组件的state。当state更新时,React会重新渲染该组件及其子组件。
使用this.setState代码栗子:
class Board extends React. Component { constructor ( props ) { super ( props) ; this . state = { squares : Array ( 9 ) . fill ( null ) , } ; } handleClick ( i ) { const squares = this . state. squares. slice ( ) ; squares[ i] = 'X' ; this . setState ( { squares : squares} ) ; } renderSquare ( i ) { return ( < Square value= { this . state. squares[ i] } onClick= { ( ) => this . handleClick ( i) } / > ) ; } render ( ) { const status = 'Next player: X' ; return ( < div> < div className= "status" > { status} < / div> < div className= "board-row" > { this . renderSquare ( 0 ) } { this . renderSquare ( 1 ) } { this . renderSquare ( 2 ) } < / div> < div className= "board-row" > { this . renderSquare ( 3 ) } { this . renderSquare ( 4 ) } { this . renderSquare ( 5 ) } < / div> < div className= "board-row" > { this . renderSquare ( 6 ) } { this . renderSquare ( 7 ) } { this . renderSquare ( 8 ) } < / div> < / div> ) ; }
}