【问题标题】:setstate isn't setting value to statesetstate 没有将值设置为状态
【发布时间】:2020-01-04 21:35:46
【问题描述】:

我在 mouseup 和 mouse leave 事件中计算它之后设置我的状态,但它没有更新它如何在 mouseup 和 mouse leave 中解决

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

onMouseMove = (e) => {
        if (!this.isDown) {
            return;
        }
        e.preventDefault();
        var x = e.pageX - this.slider.current.offsetLeft;
        var walk = x - this.startX;
        this.startX = x;
        var z = walk;
        var finalValue = this.state.left + (z / 3);
        finalValue = Math.floor(finalValue * 100) / 100;
        this.setState({ left: finalValue }, () => { });
        this.setState({ percent: false })
    }

onMouseLeave = () => {
        this.isDown = false;
        var left = this.state.left;
        for (let i = 0; i < 6; i++) {
            this.el = 306*[i]
            console.log(this.el);

            if (left<=this.el) {
             this.setState({left:this.el},()=>{})
            //  return
            }
            console.log(this.state.left);

        }
    }
    onMouseUp = () => {
        this.isDown = false;
        this.slider.current.style.cursor = 'pointer';
        var left = this.state.left;
        for (let i = 0; i < 6; i++) {
            this.el = 306*[i]
            console.log(this.el);

            if (left<=this.el) {
             this.setState({left:this.el},()=>{})
            //  return
            }
            console.log(this.state.left);

        }

    }



 render() {
            return (
                    <div className="slider-wrapper" >
                        <div onMouseDown={this.onMouseDown}
 style={this.state.percent ? this.goLeftPercent() : this.mouseMove()} 

onMouseUp={this.onMouseUp} onMouseLeave={this.onMouseLeave} onMouseMove={this.onMouseMove} 参考={this.slider} className="slider-container"> ) }

【问题讨论】:

  • 分享完整代码以便更好地理解。
  • 你是怎么调用这个函数的?
  • 它不会让我发帖
  • 我在 mouseup 和 mouseleave 事件中调用这些函数
  • 能否分享一下您的渲染方法,这样我们可以提供更好的帮助。

标签: javascript reactjs


【解决方案1】:

如果我理解正确,您可以尝试以下更改。

构造函数

constructor() {
        super();

this.onMouseLeave = this.onMouseLeave.bind(this);
this.onMouseUp = this.onMouseUp.bind(this);

}

渲染()

<li onMouseUp={this.onMouseUp} onMouseLeave={this.onMouseLeave} >

【讨论】:

  • 我使用箭头函数我还需要绑定吗?
  • 发布渲染方法。这将为您提供清晰的图片以帮助您
  • 我发布了我的渲染方法
猜你喜欢
  • 2019-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多