无法修复"setState(...): Can only update a mounted or mounting component"



有人可以告诉我这有什么问题吗:

import React, { Component, PropTypes } from 'react';
class ExampleModal extends Component {
static propTypes = {
is_shown: PropTypes.bool
}
show = () => {
console.log('The function gets called, but setState fails');
this.setState({ is_shown: true });
}
render() {
return (
<button onClick={this.show}>Press me</button>
);
}
}
export default ExampleModal;

尝试谷歌搜索,浏览文档并更改语法,但仍然没有解决方案。例如,可以通过导入上面的组件并将其放入主<div>中来使用此示例应用程序进行复制。

事实证明,Babel 需要转换类属性插件才能正确处理语法。不幸的是,Webpack 或 Babel 在任何时候都没有显示任何错误消息。似乎插件排序也很重要:如果我将转换插件放在热加载程序插件之后,问题仍然存在。

如果其他人正在解决同样的问题,这里是解决问题的 .babelrc:

{
"presets": ["stage-2", "react"],
"env": {
"development": {
"plugins": [
[
"transform-class-properties",
"react-hot-loader/babel"
]
]
}
}
}

当然,您还需要安装插件:

npm install --save-dev babel-plugin-transform-class-properties

编辑:令人尴尬,但实际上这"修复"问题的原因是数组中的拼写错误,导致反应热加载器未加载。因此,反应热加载器是罪魁祸首,但我还没有弄清楚为什么......

我相信你错过了constructor

constructor(props) {
super(props);
this.state = {
is_shown: false
};
}
show() {
console.log('The function gets called, but setState fails');
this.setState({ is_shown: true });
}
render() {
return (
<button onClick={this.show.bind(this)}>Press me</button>
);
}

为了使类方法格式一致,我在{this.show}中添加了.bind,这使thisshow()方法中指向该类。

相关内容

最新更新