我想在 render() 中调用一个函数来更新状态。但是当我这样做时,它会给我这个错误消息:
超出最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React 限制嵌套更新的数量以防止无限循环。
我不明白为什么会发生这种情况,因为我没有直接在 render() 中设置状态,而是在 setInsightUrl() 函数中设置它。
我尝试过使用不同的生命周期函数,但无法让任何函数正常工作。我不知道如何编写这个函数。
import React, { Component } from 'react'
import "../../css/tabs/Tabs.css"
import {connect} from "react-redux"
class InsightPage extends Component {
constructor() {
super();
this.state = {
insightUrlState: null
}
this.setInsightUrl = this.setInsightUrl.bind(this);
}
setInsightUrl(url) {
this.setState({
insightUrlState: url
})
console.log(this.state.insightUrlState, 'INSIGHTTTTTT URLLLLLbgnhjm,k.l')
}
render() {
this.props.sideTreeMenu.dynamicMenu.forEach(obj => {
obj.children.forEach(child => {
child.insights.forEach(insight => {
if (insight.insightName === this.props.insightNameReducer) {
{this.setInsightUrl(insight.insightURL)}
}
})
})
})
return (
<div className={this.props.drawerOpen ? "tab_container2" : "tab_container" }>
<h1>Hello from Insight</h1>
<iframe frameBorder="0" style={{width: "100%", height: "70vh"}} src="https://insighttbdashboards.verizon.com/t/DigtalAnalytics/views/Digital_Analytics/Chat_Dashboard?iframeSizedToWindow=true&:embed=y&:showAppBanner=false&:display_count=no&:showVizHome=no#2" />
</div>
)
}
}
const mapStateToProps = state => ({
drawerOpen: state.SideDrawerReducer.open,
sideTreeMenu: state.SideDrawerReducer.menu,
insightNameReducer: state.SideDrawerReducer.insightName
})
export default connect(mapStateToProps)(InsightPage);
它应该使用我传递到渲染 block 中的函数的 url 来更新状态。
最佳答案
仅仅因为您在渲染 (setInsightUrl
) 之外定义的函数中调用 setState
并不意味着您没有调用它在 render
中,当满足正确条件时,render
可能会调用 setInsightUrl
,因此可能会永远循环。
也许您只能在状态实际发生变化时才更新状态:
setInsightUrl(url) {
if (this.state.insightUrlState != url) {
this.setState({
insightUrlState: url
})
console.log(this.state.insightUrlState, 'INSIGHTTTTTT URLLLLLbgnhjm,k.l')
}
}
关于javascript - 为什么 render() 中的这个函数调用会创建无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57664900/