简体   繁体   English

使用 this 作为绑定参数时 SetState 不起作用(ReactJS)

[英]SetState not functioning while using this as a parameter to bind (ReactJS)

I have a binded function inside a map function which is activated by onClick, yet I cannot access this function because it seems that using this as a parameter stops setState working. I have a binded function inside a map function which is activated by onClick, yet I cannot access this function because it seems that using this as a parameter stops setState working. originally the setState in the buttonPress function would work, but now that i have added bind(this, (key)) to allow the key parameter to pass through, it skips setState and I can only console.log().最初 buttonPress function 中的 setState 可以工作,但现在我添加了 bind(this, (key)) 以允许 key 参数通过,它跳过 setState,我只能 console.log()。

The intention of everything is to identify what entry has been clicked and then pass it as a prop to a child class component.一切的目的是识别已单击的条目,然后将其作为道具传递给子 class 组件。

The map() function map() function

<div ref={p => this.MyMenu = p} className="mainmenu">
<p className="title">Song List</p>
    <div className="songList">
        {song.map(song => (<div onClick={this.buttonPress.bind(this, song.key)}  key={song.key}  className="song-entry">
            <h3 className="song-name">{song.name}</h3>
            <p className="song-length">{song.length}</p>
            <p className="song-desc">{song.desc}</p>
        </div>))
        }

    </div>

    </div>

and here is the function buttonPress这里是 function 按钮按下

buttonPress (key) {

    console.log(key);

    let localkey = key 


    this.setState({songchoice: localkey});

    console.log(this.state.songchoice);

    clearInterval(this.countdownInterval);
    this.setState({count:3, countdown:true, songchoice: key}, 
        ()=>{setInterval(this.countdownInterval, 3000); this.aboutTween = TweenMax.to(this.aboutSection, .8,{opacity:1, y: -100, ease: Power3.easeOut})});

} }

also a GitHub link if you'd like to look at the whole page.如果您想查看整个页面,还有一个 GitHub 链接。

Is there a specific reason to bind I don't know May be you could have tried it is a much simpler way, something like是否有特定的绑定原因我不知道也许你可以尝试过它是一种更简单的方法,比如

onClick={ () => this.buttonPress(song.key)}

I figured it out.我想到了。 SetState was actually working but because it was asynchronously set, the console log didn't happen reflect the change. SetState 实际上正在工作,但由于它是异步设置的,因此控制台日志没有发生反映更改。

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

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