我希望在深入 React 之前知道这些
1、每次调用 setState 都会引起组件的重新渲染 re-render
每次state 改变或者传入新的 props 都会调用 shouldComponentUpdate。
shouldComponentUpdate 默认返回 true,开发者可以根据自己的逻辑决定是否返回 false。
shouldComponentUpdate(nextProps, nextState) {
const vitalPropsChange = this.props.bar !== nextProps.bar;
const vitalStateChange = this.state.foo !== nextState.foo;
return vitalPropsChange || vitalStateChange;
}
// React will not re-render the component unless vitalPropsChange
// or vitalStateChange is true.注意:
不正确的 shouldComponentUpdate 逻辑可能引发错误:应该渲染的时候没有渲染,或者不应该渲染的时候却渲染了
在 shouldComponentUpdate 进行复杂的判断容易引发性能问题,可以通过 React’s Performance Tools 来查找。
我强烈建议你使用React 的性能工具来检查使用shouldComponentUpdate. 它有一个非常简单的用法:
Perf.start()
// React operations in-between are recorded for analyses.
Perf.stop()
Perf.printWasted()2、setState 对状态的改变是异步的
调用 setState 后,组件的 state 并不会立即改变。
一个经常犯的错误就是在 setState 后马上使用 this.state。
// this.state.value is initially 0
this.setState({value: this.state.value + 1});
this.setState({value: this.state.value + 1});
this.setState({value: this.state.value + 1});
// this.state.value is 1 instead of 3setState 还有另一种用法:setState(updater, [callback]),通过传递一个函数 updater。
this.setState((prevState) => {
return {value: prevState.value + 1};
});第 2 个参数是修改完状态后的回调,但是不推荐在这里写业务逻辑,一个比较不错的地方是写到 componentDidUpdate 函数里。
3、组件生命周期很重要
生命周期大概分为 3 类:
挂载:组件被创建并插入到 dom

更新:组件正在重新渲染,一般是由 props 或 state 的改变引起的

卸载:组件从 DOM 上移除

4、componentWillReceiveProps 的使用
当组件的 props 改变时需要更新 state 时使用这个方法。
componentWillReceiveProps(nextProps){
if(this.props.foo !== nextProps.foo){
this.whenFooChanges();
}
if(this.props.bar !== nextProps.bar){
this.whenBarChanges();
}
}注意:
即使 props 没有改变,也会调用 componentWillReceiveProps,因此需要在函数内部比较 this.props 和 nextProps
在一个已挂载组件接收新 props 前,componentWillReceiveProps 被调用,因此在挂载阶段是不会调用 componentWillReceiveProps 的
5、使用 React Developer Tools
React Developer Tools 可以更方便的调试 React 应用。
6、使用 Create React App
官方推出的 Create React App 让开发者已零配置的方式快速创建 React 应用。
本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!