将mobx可观察对象作为道具进行反应是否安全

时间:2020-06-16 11:54:45

标签: reactjs mobx mobx-react

说,我有一个产品模型,该模型具有10多个属性,其中一些也是对象。

{
  "product": {
    "name": "shoe",
    "brand": "....",
    "categories": {
      "abc": {
        ...
      }
    },
    ...
  }
}

我需要在react组件中更新产品,但是,该产品也有一些子组件可供其他组件查看/更改。

@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表示道具应该是不可变的,但是以下示例可以正常工作。这样安全吗?

2 个答案:

答案 0 :(得分:3)

MobX很好,这是正确的方法。

有时候,您不想更改这样的属性,而是在数据周围创建某种Model包装器(例如https://github.com/mobxjs/mobx-state-tree或它的替代品),并使用Model方法更改内容。但是您的示例也可以。

尽管您需要用ProductDetails装饰器包装observer,以便它可以对更改做出反应。 (也许您只是在示例中省略了它)

答案 1 :(得分:2)

看起来还可以。只要记住要dereference values as late as possible