我只想先显示“Jack”这个词,然后几秒钟后显示另一个数字:20。但是React.js总是同时显示它们。顺便说一句,我知道如何使用超时,我只是困惑为什么下面的代码没有逐行运行?!
import React from 'react';
import '../index.scss'
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
age: null,
};
}
longTimeFunction(input) {
var i = 0;
while(i < input) {
console.log(i)
i = i + 1
}
};
componentDidMount() {
this.setState({ username: 'JACK' })
this.longTimeFunction(30000);
this.setState({ age: '20' })
}
render() {
return (
<h1>Hello: {this.state.username} {this.state.age}</h1>
);
}
}
export default MyForm;
最佳答案
使用setTimeout
:
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
age: null,
};
}
componentDidMount() {
this.setState({ 'username': 'JACK' })
const vm = this;
setTimeout(function () {
vm.setState({ age: '20' })
}, 30000)
}
render() {
return (
<h1>Hello: {this.state.username} {this.state.age}</h1>
);
}
}
export default MyForm;
预计到达时间:通常,您不想在 JS 中阻塞执行,而是希望使用某种回调来推迟某个进程的执行。
关于javascript - 如何在React中同步操作或者说如何让react js代码逐行运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58701509/