个人技术分享

autorun 用法

监听变量变化

componentDidUpdate() {
	autorun(() => {
		console.log(this.list); // 每次 this.list 发生改变,都会触发这里

		// 对 list进行后续操作
		this.listChangeHandle();
	})
}

⚠️注意 上边的autorun,会一直保留,每次组件加载都会保留一个autorun,所以需要在组件销毁的时候移除,如下:

componentDidUpdate() {
	this.listChangeHandle = autorun(() => {
		console.log(this.list); // 每次 this.list 发生改变,都会触发这里
	})
}

componentWillUnmount() {
	// 取消订阅
	this.listChangeHandle();
}

异步操作 runInAction

async getList() {
	const list = await axios('xxxxxx', params);
	
	// 异步操作
	runInAction(() => {
		this.list = list;
	})
}