React - State - 状态管理

昨天没遇到state,今天来了

we introduce mutable state to the component. this.state is private to the component and can be changed by calling this.setState().
When the state updates, the component re-renders itself.

state是组建私有的,类似NG2 里的 class的变量,并且变化触发rerender

可以想象一下 我们在NG2的 ngIf 接受的boolean值 ngFor接受的 array或者stream或者promise
这些也会触发UI层面的重新渲染

看下写法

//this is the root component which including other comps
class CommentBox extends React.Component<any, any> {
state: any;
constructor() {
super();
this.state = { data: [
{ id: 1, author: "Pete Hunt", text: "This is one comment" },
{ id: 2, author: "Jordan Walke", text: "This is *another* comment" }
] };
}
render() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm />
</div>
)
}
}

首先state要给个默认值,就是构造的初始化时候的状态

后续如果有逻辑需要用this.setState来变化state去触发UI的变化

官网例子:

 var CommentBox = React.createClass({
getInitialState: function() {
return {data: []};
},
componentDidMount: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm />
</div>
);
}
});

他这里的初始化用了 getInitialState,对应咱们ts的构造.
里面变化了data触发rerender

componentDidMount 是组建生命周期中当组建渲染到DOM后的callback
这个可能类似于ngAfterView

state还是对当前组建状态的具体描述

连input value都要记录…他这算是snapshot吧

 var CommentForm = React.createClass({
getInitialState: function() {
return {author: '', text: ''};
},
handleAuthorChange: function(e) {
this.setState({author: e.target.value});
},
handleTextChange: function(e) {
this.setState({text: e.target.value});
},
render: function() {
return (
<form className="commentForm">
<input
type="text"
placeholder="Your name"
value={this.state.author}
onChange={this.handleAuthorChange}
/>
<input
type="text"
placeholder="Say something..."
value={this.state.text}
onChange={this.handleTextChange}
/>
<input type="submit" value="Post" />
</form>
);
}
});

A common way to inform React of a data change is by calling setState(data, callback). This method merges data into this.state and re-renders the component. When the component finishes re-rendering, the optional callback is called. Most of the time you’ll never need to provide a callback since React will take care of keeping your UI up-to-date for you.

这里说明了callback发生的时间,是在渲染后