比如说,我有一个产品模型,它有10多个属性,其中一些也是对象。
{
"product": {
"name": "shoe",
"brand": "....",
"categories": {
"abc": {
...
}
},
...
}
}
我需要在一个react组件中更新Product,然而,Product也有一些子代被其他组件查看改变。
@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说道具应该是不可变的,然而下面的例子却能正常工作。这样做安全吗?
用MobX完全可以,这是正确的方式。
有时你不想这样改变属性,而是在你的数据周围创建一些Model包装器(类似于 https:/github.commobxjsmobx-state-tree。 或其替代品)并使用Model方法来改变东西。但你的例子也可以。
虽然你需要将 ProductDetails
与 observer
装饰器,这样它就可以对变化做出反应。(也许你只是在你的例子中省略了它)
看起来还不错。只要记住 尽可能晚地解除参考值.