尝试使用 await 时出现意外的严格模式保留字"



这里是代码示例:


class App extends Component {
constructor() {
super();
this.state = {
currentColor: "red"
};
while(1){
await this.changeColor();
}
}
changeColor = async () => {
console.log("123")
setTimeout(() => {
this.setState({
currentColor: "yellow"
});
setTimeout(() => {
this.setState({
currentColor: "green"
});
setTimeout(() => {
this.setState({
currentColor: "red"
});
}, 100);
}, 200);
}, 300);
};
render() {
return (
<div>
<div
className={this.state.currentColor}
style={{ width: "100px", height: "100px" }}
/>
</div>
);
}
}

当我在changeColor((前面添加wait时,我得到了一个"意外的严格模式保留字"错误。在线代码:https://stackblitz.com/edit/react-cm4jdq.(我想纠正红绿灯演示(

您只能在异步函数的上下文中使用await。构造函数不是异步的,因此出现错误。构造函数不能声明为async,因为构造函数必须返回构造的对象,而async函数返回promise。

好消息是,changeColor不需要异步,也不需要在无休止的while循环中等待它。如果希望它连续运行,请使用setInterval而不是setTimeout。

我还建议您循环使用一组颜色,而不是对每种颜色重复setTimeout/setState。


const classnames = ['yellow', 'green', 'red'];
function App () {
const [colorIndex, setColorIndex] = React.useState(0);
React.useEffect(() => {
const interval = setInterval(() => {
this.setState({
colorIndex: (colorIndex + 1) % colors.length
}), 100);
});
// cancel interval on unmount
return () => clearInterval(interval);
}, [])
return <div className={classnames[colorIndex]}> ... </div>
}

最新更新