本文是我做React开发过程中碰到的一些错误以及原因分析,算是给自己做个总结吧。
生命周期
React定义了一系列的函数,会在特定的生命周期内调用:
- 装载过程:组件第一次在DOM树中渲染的过程
- 更新过程:组件重新渲染的过程
- 卸载过程:组件从DOM中删除的过程
装载过程依次调用的函数:
- getInitialState 和 getDefaultProps: 在ES6语法函数不会产生作用
- componentWillMount:
- render: 必须要实现,纯函数:根据this.state,this.props返回结果,不产生副作用
- componentDidMount: render返回的仅仅是虚拟dom-jsx。会在所有组件render之后,才完成装载,这个时候才会依次调动各个组件的componentDidMount作为装载过程的守收尾。
更新过程调用的函数:
- componentWillReveiveProps
- shouldComponentUpdate 高性能渲染必须要实现的方法
- componentWillUpdate
- render
- componentDidUpdate
卸载过程:
- componentWillUnmount 适合一些清理性的工作
Use the defaultValue
or value
props instead of setting children on <textarea>
原因分析:组件使用了textarea,并直接在textarea标签内部做了属性绑定:
<div className="form-group">
<label htmlFor="ipt-about">个人介绍</label>
<textarea className="form-control" id="ipt-about" placeholder="">{this.state.about}</textarea>
</div>
解决方案:为textarea增加属性
value={this.state.about}
只能返回一个节点
export default class App extends React.Component {
// render 只能返回一个节点,所以需要外面包一层div,即使这个div没什么卵用
render() {
return (
<div>
<Router history={browserHistory}>
<Route path="/" component={Index}>
<Route path="/topic/:id" component={TopicDetail} />
</Route>
</Router>
</div>
)
}
}
动态创建自组件必须包含key
为什么?性能问题,防止无谓的更新
ref
用于获取原生dom,方便使用jQuery操作原生dom.
React组件分离不够彻底,但足够内聚,如何扬长避短呢?
拆分组件时,足够颗粒化,足够看清楚组件的关系。
React组件嵌套很深如何处理?
全局状态的管理,默认有个Store,所有数据都来自一个Store,不会有信息传递链很长的问题。
自己开发组件库如何让别人使用?
组件内部使用props传递,缺点为了传递给内层的组件,外层组件需要层层传递store,即使外层组件根本不需要这个store。
Context上下文环境。