【发布时间】:2017-03-12 08:07:11
【问题描述】:
我正在尝试执行本 ReactJS 教程的第 15 步:React.js Introduction For People Who Know Just Enough jQuery To Get By
作者推荐如下:
overflowAlert: function() {
if (this.remainingCharacters() < 0) {
return (
<div className="alert alert-warning">
<strong>Oops! Too Long:</strong>
</div>
);
} else {
return "";
}
},
render() {
...
{ this.overflowAlert() }
...
}
我尝试执行以下操作(我觉得没问题):
// initialized "warnText" inside "getInitialState"
overflowAlert: function() {
if (this.remainingCharacters() < 0) {
this.setState({ warnText: "Oops! Too Long:" });
} else {
this.setState({ warnText: "" });
}
},
render() {
...
{ this.overflowAlert() }
<div>{this.state.warnText}</div>
...
}
我在 Chrome 开发工具的控制台中收到以下错误:
在现有状态转换期间无法更新(例如在
render或其他组件的构造函数中)。渲染方法应该是 props 和 state 的纯函数;构造函数的副作用是 反模式,但可以移动到componentWillMount。
这是JSbin demo。为什么我的解决方案不起作用?这个错误是什么意思?
【问题讨论】:
-
想一想:组件在状态更新时会重新渲染,所以如果你在渲染方法中更新状态,那将是一个无限循环。你想在这里完成什么?每当有人输入文本或其他内容时更新状态。
-
@AndrewLi 清醒的回答。继续并将其作为答案归档,我会将其标记为正确。我想在这里完成什么:嗯,我试图以自己的方式做,而不看解决方案,这就是我想出的。
标签: javascript reactjs