首页 > 解决方案 > 将 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 应该是不可变的,但是下面的例子工作得很好。这样做安全吗?

标签: reactjsmobxmobx-react

解决方案


MobX 完全没问题,这是正确的方法。

有时您不想像这样更改属性,而是在您的数据周围创建某种模型包装器(例如https://github.com/mobxjs/mobx-state-tree或其替代品)并使用模型方法来更改东西。但是你的例子也可以。

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


推荐阅读