繁体   English   中英

Map函数循环并给出错误-React

[英]Map function loops and gives error - React

我创建了通过单击菜单项创建的选项卡。 之后,我希望仅在将鼠标悬停在<li>父对象上时才显示关闭的“ X”。

我认为这是我尝试绘制“ X”悬停时尚未创建的地图问题,但我不知道如何解决。 为什么会出现此错误? 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)上的绑定,这导致它直接调用它

公平地说,您可能应该将所有(this)一起删除(因此即使在映射函数中也没有绑定)

{this.props.tabsLi.map((value, index) =>
    <li key={index} onMouseOver={this.showCloseTabs.bind(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>
)}         

要使用类属性,可以更改方法的声明,例如

showCloseTabs = (e) => { /* ... */ }

在这两种情况下,您都可以将onMouseOver属性更改为

onMouseOver={this.showCloseTabs}

并完成它:)

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

此函数正在执行setState ,从而导致错误:

在现有状态转换期间(例如在render内)无法更新。 渲染方法应该纯粹是props和state的函数。

需要传递给onMouseOveronClick是对该函数的引用。 如果是showCloseTabs ,它将是:

onMouseOver={this.showCloseTabs}

如果您需要传递参数:

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

render调用时,还将方法绑定到render会创建新函数。 相反,您可以将其绑定到构造函数中:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM