将 mobx 可观察对象作为道具传递给反应组件是否安全

Is it safe to pass mobx observable objects as props to react components

比如说,我有一个 Product 模型,它有 10 多个属性,其中一些也是对象。

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

我需要在 React 组件中更新产品,但是,产品也有一些子组件要被其他组件 viewed/changed。

@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 或其替代品)并使用模型方法来更改内容。不过你的例子也可以。

虽然您需要用 observer 装饰器包装 ProductDetails 以便它可以对更改做出反应。 (也许你只是在你的例子中省略了它)

看起来不错。记得 dereference values as late as possible.