reactjs - 将 mobx 可观察对象作为道具传递给反应组件是否安全
问题描述
比如说,我有一个 Product 模型,它有 10 多个属性,其中一些也是 objects 。
{
"product": {
"name": "shoe",
"brand": "....",
"categories": {
"abc": {
...
}
},
...
}
}
我需要在反应组件中更新产品,但是,产品也有一些子组件可以被其他组件查看/更改。
@observer
class ProductContainer extends Component {
@observable product;
render() {
return (
<ProductDetails product={product} />
)
}
}
@observer
class ProductDetails extends Component {
static propTypes = {
product: PropTypes.any
}
@autobind
@action
handleChangeName(event) {
const {product} = this.props;
product.name = event.target.value;
}
render() {
const {product} = this.props;
return (
<form>
<label>Name: <input type="text" onChange={this.handleChangeName} /> </label>
<CategoryView categories={product.categories} />
</form>
);
}
}
如示例中所见,我有内部组件,例如CategoryView
我将可观察对象的子对象(它也是可观察的)传递给这些组件。
我在示例中所做的是我不更改product
道具引用,而是更改它的子项和属性(例如名称)。
React 说 props 应该是不可变的,但是下面的例子工作得很好。这样做安全吗?
解决方案
MobX 完全没问题,这是正确的方法。
有时您不想像这样更改属性,而是在您的数据周围创建某种模型包装器(例如https://github.com/mobxjs/mobx-state-tree或其替代品)并使用模型方法来更改东西。但是你的例子也可以。
尽管您需要ProductDetails
使用observer
装饰器进行包装,以便它可以对更改做出反应。(也许你只是在你的例子中省略了它)
推荐阅读
- nix - 使用 nix-store --restore 安装源
- c# - 将表行映射到带有 EF 核心的 DDD 值对象
- spring-boot - R2DBC 无法使用 h2 协议创建连接
- python - 如何同时遍历一个列表和一个 Daraframe 列表
- javascript - 从 JSON 对象中获取最大值
- python - 从python中的子目录访问函数,在哪里放置__init__.py文件?
- google-visualization - 如何在谷歌图表中用负值为图形下的区域着色
- r - R中的子集数据帧以配对列表中的两个值为条件
- javascript - 如何在节点中异步增量查询某些同步点的子进程(不使事情复杂化)
- wso2 - api manager-如何将master-datasource xml文件配置到我们的身份服务器db而不是api manager db