gpt4 book ai didi

javascript - 等到 `this.state` 被设置为运行函数之前的时间段

转载 作者:行者123 更新时间:2023-11-29 19:04:48 26 4
gpt4 key购买 nike

我有一个按钮,它有 3 个状态。根据触发的状态,它应该进行提取以发布此数据。

基本上,我希望它等到 this.state.favourite 值设置超过 200 毫秒。然后它应该触发提取。

它不应该发布多个提取的,

我尝试使用 lodash 的 _.debounce,但没有任何效果。它仍然立即运行该功能。

我也把它放在一个CodePen .

class Switch extends React.Component {
constructor() {
super();
this.state = {
favourite: 0
}
}

handleClick() {
this.setState((prevState) => ({
favourite: (prevState.favourite + 1) % 3
}));
return _.debounce(this.favChosen(), 1000)
}
favChosen(){
if (this.state.favourite === 0) {
return this.testConsole1();
} else if (this.state.favourite === 1) {
return this.testConsole2();
} else if (this.state.favourite === 2) {
return this.testConsole3();
}
testConsole1() {
console.log('This will be a fetch 1')
}
testConsole2() {
console.log('This will be a fetch 2')
}
testConsole3() {
console.log('This will be a fetch 3')
}
render () {
const { favourite } = this.state;
const fill = favourite === 0 ? "grey" :
favourite === 1 ? "green" : "red";
return (
<button className="favStar" onClick={this.handleClick.bind(this)} >
<svg width="100" height="100">
<g>
<path id="svg_2" d="m0,38l37,0l11,-38l11,38l37,0l-30,23l11,38l-30,-23l-30,23l11,-38l-30,-23l0,0z" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke-width="0" fill={fill} />
</g>
</svg>
</button>
);
}
}

React.render( <Switch />, document.getElementById( "page" ) );

最佳答案

您没有正确使用debounce

  constructor() {
super();
this.state = {
favourite: 0
}

this.favChosen = _.debounce(this.favChosenRaw, 1000);
}

handleClick() {
this.setState((prevState) => ({
favourite: (prevState.favourite + 1) % 3
}));

this.favChosen()

}
favChosenRaw(){....

工作 fiddle :

http://codepen.io/anon/pen/GmELKo?editors=1010

关于javascript - 等到 `this.state` 被设置为运行函数之前的时间段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43750647/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com