gpt4 book ai didi

javascript - 映射函数循环并给出错误 - React

转载 作者:行者123 更新时间:2023-11-30 09:13:23 25 4
gpt4 key购买 nike

我已经创建了通过单击菜单项创建的选项卡。在那之后,我希望关闭的“X”只在悬停在 <li> 上时出现。 parent 。

当我尝试绘制“X”悬停时,我认为这是一个尚未创建的 map 问题,但我不知道如何解决它。为什么会出现此错误? Can not update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.

class LiTabs extends Component{
constructor(props, context){
super(props, context);

["showCloseTabs",].forEach((method) => {
this[method] = this[method].bind(this);
});

this.state = {
closeTabs: false,
};
}

showCloseTabs(e){
this.setState({
closeTabs : true,
})
console.log(e);
}

render(){
return(
<>
{this.props.tabsLi.map((value, index) =>
<li key={index} onMouseOver={this.showCloseTabs(this)}>
<span>{value}</span>
<div onClick={this.props.removeTab.bind(this, value, index)} >
{this.state.closeTabs === true && (
<Icon icon="cerrar" className='ico-cerrar'/>
)}
</div>
</li>
)}
</>
);
}
}

最佳答案

this.showCloseTabs(this) 是 JavaScript 中的函数调用,这意味着调用 render 方法时会调用该函数。

此函数正在执行导致错误的 setState:

Can not update during an existing state transition (such as within render). Render methods should be a pure function of props and state.

需要传递给 onMouseOveronClick 的是对函数的引用。对于 showCloseTabs,这将是:

onMouseOver={this.showCloseTabs}

如果需要传递参数:

onMouseOver={(e) => this.showCloseTabs(e)}

同时绑定(bind) render 中的方法会在调用 render 时创建新函数。相反,您可以在构造函数中绑定(bind)它:

constructor() {
this.onMouseOver = this.onMouseOver.bind(this);
}

关于javascript - 映射函数循环并给出错误 - React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56900397/

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