gpt4 book ai didi

reactjs - 当 'action'/'runInAction'在mobx react中真的需要

转载 作者:行者123 更新时间:2023-12-05 01:37:25 28 4
gpt4 key购买 nike

谁能给我解释一下真正的区别是什么以及为什么这里的两个例子都一样:

1) 通过存储文件中的 action/runInAction 更改可观察状态:

颜色存储文件:

@observable
color='red'

@action
setColor(){
this.color='blue'
}

2)通过组件本身改变状态(这被认为是不好的做法):

react 组件文件:

onClick = () => this.props.colorStore.color='blue' //still working...

最佳答案

Mobx action 正在执行批处理,类似于 ReactJS 批处理多个更改的方式。

当您使用 reactjs click 处理程序时,react 会自动批处理其中发生的更改,因此您不会多次看到组件渲染,但是,如果您调用 setColor一些其他事件,比如说在加载一些数据之后,多次调用更改 setColor 中的可观察对象,这将触发观察者三次,组件将被渲染三次。

当你用 @action 装饰器包装你的函数或者你使用 runInAction 函数时,只会使用最后一个值(green in the下面的代码)并且该组件将只呈现一次。

setColor(){
// this will render three times
this.color='blue'
this.color='red'
this.color='green'
}

仅响应一次的 vanilla mobx 示例:

import { runInAction, observable, reaction, toJS } from "mobx";

const test = observable({
name: "sonic",
nick: "speed demon"
});

// console.log will be called only once with the value "name: 3"
reaction(
() => toJS(test),
data => console.log(`name: ${data.name}`)
);

runInAction(() => {
test.name = "1";
test.name = "2";
test.name = "3";
});

查看codesandbox

另请查看 github 存储库上的讨论:is @action really necessary?

关于reactjs - 当 'action'/'runInAction'在mobx react中真的需要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61055462/

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