setstate不是将值设置为state

时间:2019-09-01 14:41:42

标签: javascript reactjs

我在mouseup和mouse离开事件中计算完状态后就设置了状态,但没有更新如何解决mouseup和mouse离开事件中的状态

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} ref = {this.slider} className =“ slider-container”>                 )             }

1 个答案:

答案 0 :(得分:0)

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

构造函数

constructor() {
        super();

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

}

Render()

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