我是ReactJS的新手,正在尝试一个简单的项目.基本上,该代码段会从数组中创建一个朋友列表,并显示朋友的总数.
由于某种原因,当我添加一个新朋友时,我意识到incrementFriendsCount函数抛出"最大调用堆栈超出错误"
下面的代码片段也可以在JSFiddle上找到.
var HelloUser = React.createClass({
getInitialState: function() {
return {
name: "Toyosi",
friends: ["Susanna", "Jibola", "Worreva"],
friendsCount: 0
}
},
addFriends: function(friend) {
this.setState({
friends: this.state.friends.concat([friend])
});
},
componentWillMount: function() {
this.setState({
friendsCount: this.state.friends.length
});
},
incrementFriendsCount: function() {
this.setState({
friendsCount: this.state.friends.length
});
},
render: function() {
return ( < div >
Villain: {
this.state.name
}, No of friends: {
this.state.friendsCount
} < br / >
< AddingTheFriend addNew = {
this.addFriends
}
incCount = {
this.incrementFriendsCount
}
/>
<ListFriends enemies={this.state.friends} / >
< /div>
);
}
});
var ListFriends = React.createClass({
propTypes: {
enemies: React.PropTypes.array.isRequired
},
render: function() {
var allFriends = this.props.enemies.map(function(friend){
return <li>{friend}</li > ;
});
return ( < div > Her evil friends:
< ul > {
allFriends
} < /ul>
</div >
)
}
});
var AddingTheFriend = React.createClass({
getInitialState: function() {
return {
newFriend: ''
}
},
propTypes: {
addNew: React.PropTypes.func.isRequired
},
updateNewFriend: function(change) {
this.setState({
newFriend: change.target.value
});
},
addTheFriend: function() {
this.props.addNew(this.state.newFriend);
this.setState({
newFriend: ''
})
},
componentWillReceiveProps: function() {
this.props.incCount();
},
render: function() {
return ( < div >
< input type = "text"
value = {
this.state.newFriend
}
onChange = {
this.updateNewFriend
}
/>
<button type="button" onClick={this.addTheFriend}>Add Friend</button >
< /div>
)
}
});
React.render(<HelloUser / > , document.getElementById('app'));Run Code Online (Sandbox Code Playgroud)
<script src="http://fb.me/react-js-fiddle-integration.js"></script>
<div id="app"></div>Run Code Online (Sandbox Code Playgroud)
如果有人能够更多地了解为什么会抛出这个错误,我将不胜感激.
hur*_*rtz 12
作为使用react时具有相同错误输出的人的未来参考:使用两者运行应用程序时也会发生此错误
所以:当您使用--hot运行服务器并且在webpack配置中启用了hotModuleReplacementPlugin时,您将遇到组件将递归更新的情况,从而生成OP提到的错误消息.
简单的解决方案:省略两件事之一,例如省略"--hot",因为你已经使用了插件.
| 归档时间: |
|
| 查看次数: |
33496 次 |
| 最近记录: |