[英]Why does the component is not re-rendering when i add @action decorator to an react event handler function
The below react component is not re-rendering when I add @action decorator to the class member fn.当我将@action 装饰器添加到 class 成员 fn 时,以下反应组件不会重新渲染。
import { observable, action } from "mobx";
import { observer } from "mobx-react";
import * as React from "react";
import { render } from "react-dom";
@observer
class PriceCounter extends React.Component {
@observable price = 0;
@action
setPrice = () => {
this.price = this.price + 1;
};
@action
currentPrice = () => {
return this.price;
}
render() {
return (
<div>
<span className="text-3xl">Total: {this.currentPrice()}</span>
<button onClick={this.setPrice}>Change details</button>
</div>
);
}
}
render(<PriceCounter />, document.getElementById("root"));
Why?
为什么? Explanation needed.
需要解释。
Either you can use this.price to show the updated value of price.您可以使用 this.price 来显示价格的更新值。 Or you can use computed decorator to do this.
或者您可以使用计算装饰器来执行此操作。
@observer
class PriceCounter extends React.Component {
@observable price = 0;
@action
setPrice = () => {
this.price = this.price + 1;
};
@computed
get currentPrice() {
return this.price;
}
render() {
return (
<div>
<span className="text-3xl">Total: {this.currentPrice}</span>
<button onClick={this.setPrice}>Change details</button>
</div>
);
}
}
or或者
@observer
class PriceCounter extends React.Component {
@observable price = 0;
@action
setPrice = () => {
this.price = this.price + 1;
};
@action
currentPrice = () => {
return this.price;
};
render() {
return (
<div>
<span className="text-3xl">Total: {this.price}</span>
<button onClick={this.setPrice}>Change details</button>
</div>
);
}
}
This is a wrong usage of action.这是对动作的错误用法。
@action
is expected to be wrapped around a function in which observables are changed. @action
预计将包裹在 function 周围,其中可观察到的内容已更改。 Here, you are not changing any observables in currentPrice
function.在这里,您没有更改
currentPrice
function 中的任何可观察值。
Since render is a tracked function in mobx-react, if you are not wrapping currentPrice
function with action & if you call this.currentPrice()
mobx tracks observables used in that function.由于渲染是 mobx-react 中跟踪的 function,如果你没有用 action 包裹
currentPrice
function 并且如果你调用this.currentPrice()
mobx 跟踪在 ZC38541AB5074C178 中使用的 observables
If you are wrapping functions used in a tracked function with action mobx doesn't know if you intend to track observables or do you want to run tracked functions after the function is executed.如果您使用动作包装跟踪 function 中使用的函数,则 mobx 不知道您是否打算跟踪 observables 或者您想在 function 执行后运行跟踪函数。
Actions should only, and always, be used on functions that modify state.操作应仅且始终用于修改 state 的函数。 Have a look at When to use actions
查看何时使用操作
In the example you mentioned, currentPrice
method is not modifying the state.在您提到的示例中,
currentPrice
方法没有修改 state。 So you need not use action decorator to that.所以你不需要使用动作装饰器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.