正确使用refs
不建议写法:
let Progress = React.createClass({
show: function(){
this.refs.modal.show();
},
render: function() {
return (
<ProgressFormModal ref="modal"/>
);
}
});
正确写法:
let Progress = React.createClass({
show: function(){
this.modal.show();//注意这儿的this.refs.modal已被替换成this.modal
},
render: function() {
return (
<ProgressFormModal ref={ com => { this.modal=com } }/>
);
}
});
正确使用props和state
不能直接修改state的状态
this.state.comment = 'Hello';//不正确的更新
props和state可能是异步的
示例:
//可能失败
this.setState({
counter: this.state.counter + this.props.increment,
});
正确的用法:
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}));
setState可能不会立即修改this.state,如果你在setState之后立马使用this.state去取值可能返回的是旧的值。
setState这个方法可以接收两个参数,如下形式:
setState(nextState, callback)
它接收一个callback,它状态得到更新后,会执行这个callback,不过更推荐在componentDidUpdate中调用相关逻辑。
避免产生新的闭包
在子组件中,我们要避免以下写法
<input
type="text"
value={model.name}
onChange={(e) => { model.name = e.target.value }}
placeholder="Your Name"/>
正确写法:
<input
type="text"
value={model.name}
onChange={this.handleChange}
placeholder="Your Name"/>
这样可以避免每次父组件重新渲染的时候,创建新的函数;