gpt4 book ai didi

javascript - 超出最大调用堆栈大小 - Connected React Component

转载 作者:行者123 更新时间:2023-11-29 16:05:00 25 4
gpt4 key购买 nike

我一辈子都弄不明白为什么会出错:

Maximum call stack size exceeded

运行此代码时。如果我注释掉:

const tabs = this.getTabs(breakpoints, panels, selectedTab);

错误消失了。我什至注释掉了其他 setState() 调用以尝试缩小问题所在的范围。

代码(去掉多余的函数):

export default class SearchTabs extends Component {
constructor() {
super();
this.state = {
filters: null,
filter: null,
isDropdownOpen: false,
selectedFilter: null,
};

this.getTabs = this.getTabs.bind(this);
this.tabChanged = this.tabChanged.bind(this);
this.setSelectedFilter = this.setSelectedFilter.bind(this);

this.closeDropdown = this.closeDropdown.bind(this);
this.openDropdown = this.openDropdown.bind(this);
}

componentDidMount() {
const { panels } = this.props;
if (!panels || !panels.members || panels.members.length === 0) {
this.props.fetchSearch();
}
}


getTabs(breakpoints, panels, selectedTab) {
const tabs = panels.member.map((panel, idx) => {
const { id: panelId, headline } = panel;
const url = getHeaderLogo(panel, 50);
const item = url ? <img src={url} alt={headline} /> : headline;

const classname = classNames([
searchResultsTheme.tabItem,
(idx === selectedTab) ? searchResultsTheme.active : null,
]);

this.setState({ filter: this.renderFilters(
panel,
breakpoints,
this.setSelectedFilter,
this.state.selectedFilter,
this.state.isDropdownOpen,
) || null });

return (
<TabItem
key={panelId}
classname={`${classname} search-tab`}
headline={headline}
idx={idx}
content={item}
onclick={this.tabChanged(idx, headline)}
/>
);
});

return tabs;
}

render() {
const { panels, selectedTab } = this.props;

if (!panels || panels.length === 0) return null;

const tabs = this.getTabs(breakpoints, panels, selectedTab);

return (
<div className={searchResultsTheme.filters}>
<ul className={`${searchResultsTheme.tabs} ft-search-tabs`}>{tabs}</ul>
<div className={searchResultsTheme.dropdown}>{this.state.filter}</div>
</div>
);
}
}

export const TabItem = ({ classname, content, onclick, key }) => (
<li key={key} className={`${classname} tab-item`} onClick={onclick} >{content}</li>
);

最佳答案

因为这个循环:

  render  ----->   getTabs  ----->  setState -----
^ |
| |
|____________________________________________v

您正在从渲染器调用 getTabs 方法,并在其中执行 setStatesetState 将触发重新渲染,再次 getTabs ..... 无限循环.

getTabs 方法中删除 setState,它将起作用。

这里还有一个问题:

onclick={this.tabChanged(idx, headline)}

我们需要为 onClick 事件分配一个函数,我们不需要调用它,但是在这里你调用那个方法,使用这个:

onclick={() => this.tabChanged(idx, headline)}

关于javascript - 超出最大调用堆栈大小 - Connected React Component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45823050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com