设置状态:setState替换状态:replaceState设置属性:setProps替换属性:replaceProps强制更新:forceUpdate获取DOM节点:findDOMNode判断组件挂
import React,{ Component,Fragment } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import PropTypes from 'prop-types';
class Clock extends Component{
constructor(props){
super(props);
this.state={
countNum:0
}
this.addCount=this.addCount.bind(this);
}
addCount(){
.setState({
countNum:this.state.countNum+1
})
}
render(){
return(
<Fragment>
<button onClick={this.addCount}>点击计数</button>
<p>{this.state.countNum}</p>
</Fragment>
)
}
}
ReactDOM.render(
<div>
<Clock />
</div>,document.getElementById('example')
);
serviceWorker.unregister();
this.state.comment = 'Hello';
this.setState({comment: 'Hello'});
// Wrong
.setState({
counter: this.state.counter + .props.increment,});
Correct
this.setState((prevState,props) => ({
counter: prevState.counter + props.increment
}));
constructor(props) {
super(props);
this.state = {
posts: [],comments: []
};
}
componentDidMount() {
fetchPosts().then(response => {
.setState({
posts: response.posts
});
});
fetchComments().then(response =>.setState({
comments: response.comments
});
});
}
componentDidMount() {
this.mounted = true;
}
componentWillUnmount() {
false;
}
总结