【发布时间】:2018-04-06 17:23:59
【问题描述】:
警告:setState(...):只能更新已安装或正在安装的组件。这通常意味着您在未安装的组件上调用了 setState()。这是无操作的。
我在 Stack Overflow 上阅读了很多这些解决方案,但仍然完全不知道为什么会发生这种情况以及如何解决这个问题。
我有我的图表组件,它呈现页面,组件已安装。当我将鼠标悬停在图表值 (onValueMouseOver) 上时,即出现错误。我只是不明白如果我能够将鼠标悬停在我的组件上,它是如何被视为未安装的。
我尝试创建一个单独的 this.mounted 变量,我将其设置为真/假,具体取决于 componentWillMount 和 componentWillUnmount,并且仅在它们为真时使用 setState。下面的代码输出“挂载”消息(绝不是“卸载”消息),但它在启动时输出到控制台的值“真”,我假设因为我在构造函数中绑定了这些方法。但是当我将鼠标悬停时,会记录“假”。它没有记录错误,但仍然没有设置值,我需要它来做。
如果能指导我以“正确的方式”来处理这种情况,我们将不胜感激。我已经在几个地方使用了这种精确的方法,并且在我更新我的一些库和 webpack 配置之前它们都可以正常工作。
这是我的代码。我正在使用react-vis。
class Chart extends Component {
constructor(props) {
super(props);
this.mounted = false;
this.state = {
value: null
};
this.rememberValue = this.rememberValue.bind(this);
this.forgetValue = this.forgetValue.bind(this);
}
componentWillMount() {
console.log('mounting');
this.mounted = true;
}
componentWillUnmount() {
console.log('unmounting');
this.mounted = false;
}
rememberValue(value) {
console.log(this.mounted);
if (this.mounted) {
this.setState({value});
}
}
forgetValue() {
console.log(this.mounted);
if (this.mounted) {
this.setState({
value: null
});
}
}
render() {
const { series } = this.props;
const { value } = this.state;
return (
<XYPlot />
<LineMarkSeries
data={series.data}
onValueMouseOver={this.rememberValue}
onValueMouseOut={this.forgetValue}
/>
<XAxis />
<YAxis />
{value && <Hint value={value} {...this.props} />}
</XYPlot>
);
}
}
【问题讨论】:
-
forgetValue中的 if 条件是否应该是!this.mounted?这是一个事件处理程序,当您将this.mounted设置为 false 时,它可以调用setState。 -
糟糕。不,我的错字。更新中...
-
尝试将您的
componentWillMount更改为componentDidMount并从您的constructor中删除您的this.mounted分配。componentWillMount会产生意想不到的行为,实际上会在 React +17 中贬值 -
这似乎对行为没有任何影响。 MouseOver 事件只会记录
this.mounted = undefined的变化。
标签: javascript reactjs