setTimeout(fn,0):指定某个任务在主线程最早可得的空闲时间执行,尽可能早得执行。它在"任务队列"的尾部添加一个事件,因此要等到同步任务和"任务队列"现有的事件都处理完,才会得到执行。
- 函数去抖:debounce(lodash)
- 轮询任务
- 延缓js引擎的调用
import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Select } from 'antd';
const OPTIONS = ['Apples', 'Nails', 'Bananas', 'Helicopters'];
class SelectWithHiddenSelectedOptions extends React.Component {
state = {
selectedItems: []
};
handleSelect = value => {
console.log('handleSelect value', value, this.state.selectedItems)
// 解决方法1
this.setState({
selectedItems: value
}, () => {
// 在此处才能取到最新的this.state.selectedItems的值
console.log('handleSelect value2', this.state.selectedItems)
})
// 解决方法2
setTimeout(() => {
this.setState({
selectedItems: value
})
console.log('handleSelect value3', this.state.selectedItems)
}, 100);
}
handleChange = selectedItems => {
this.setState({ selectedItems });
};
render() {
const { selectedItems } = this.state;
const filteredOptions = OPTIONS.filter(o => !selectedItems.includes(o));
return (
<Select
mode="tags"
tokenSeparators={[',']}
placeholder="Inserted are removed"
value={selectedItems}
onChange={this.handleChange}
onSelect={this.handleSelect}
style={{ width: '100%' }}
>
{filteredOptions.map(item => (
<Select.Option key={item} value={item}>
{item}
</Select.Option>
))}
</Select>
);
}
}
ReactDOM.render(<SelectWithHiddenSelectedOptions />, document.getElementById('container'));
【setTimeout】:https://segmentfault.com/a/1190000013538587