我是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'));
<script src="http://fb.me/react-js-fiddle-integration.js"></script>
<div id="app"></div>
你在componentWillReceiveProps
中调用this.props.incCount
,这设置了父组件的状态,效果将是再次渲染AddingTheFriend
,再次调用this.props.incCount
。因此栈溢出。
另一个建议是,一般来说,您要小心,在尽可能少的组件中尽可能少地使用setState
。只需在将新好友连接到父组件状态的同时增加好友数。
这是代码依赖-在我看来比JSFiddle好得多。
作为将来使用react时输出相同错误的人的参考:如果同时使用
运行应用程序,也会出现此错误。- <
- webpack-dev-server——热/gh>
- 新webpack.HotModuleReplacementPlugin ()
所以:当你用——hot运行你的服务器,并且在你的webpack配置中也启用了hotModuleReplacementPlugin,那么你将进入你的组件将递归更新的情况,从而生成OP提到的错误信息。
简单的解决方案:省略这两件事中的一件,例如省略"——hot",因为你已经使用了这个插件。
在我的例子中,它是一个无限循环,或者如果你喜欢一个明显的逻辑错误。