多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## React开发遇到的问题汇总 ### 2016/2/29 16:20 ### 错误1: getInitialState里 setState ``` Uncaught Error: Invariant Violation: setState(...): Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state. ``` 1. 出现原因 由于在 ``getInitialState`` 方法里面调用了 ``this.setState()``方法,导致报这个错误 2. 解决方案 ``getInitialState`` 里面 设置 ``this.setState()`` 的代码,放到 ``componentDidMount``里面去 具体可以看:[Stackoverflow的解决方案](http://stackoverflow.com/questions/31420402/why-does-this-error-exist-invariant-violation-cannot-update-during-an-existin) --- #### 错误2:Ajax 处理时,组件已经卸载了的问题 ~~~ Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component. ~~~ **React Ajax,返回数据的时候,组件已经写在的问题解决方案?** >描述:Ajax请求还没有请求结束,组件已经卸载了。 会报错,告诉你不能对写在的组件进行 setState 操作。 比如:Ajax请求,发送出去了, 还没有请求到结果,用户已经点击跳转到其他页面了。跳转到其他页面后, React 组件就卸载了, 去加载另外一个React-router匹配的组件。 这个时候,等AJax 请求结束了, 执行回调方法,对组件进行 setState, 就报错了。 解决方案:React卸载,就中断Ajax的请求,这个方法也是官网推荐的。 ~~~ componentDidMount(){ //Model.getScriptTypes 封装的就是一个 $.ajax 方法。 return $.ajax({}) 对象 this.ajaxGetScriptTypes = Model.getScriptTypes(function (result) { that.setState({scriptTypeData: result.data}) }) } /** * 组件卸载前的操作 */ componentWillUnmount() { this.ajaxGetScriptTypes.abort(); this.ajaxGetScriptlist.abort(); } ~~~