简体   繁体   中英

setstate isn't setting value to state

i'm setting my state after calculating it in mouseup and mouse leave event but it's not updating it how to solve in mouseup and 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} ref={this.slider} className="slider-container"> ) }

If I understand correctly you can try the below changes.

Constructor

constructor() {
        super();

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

}

Render()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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