reactjs - 在父组件的 ViewStore 中跟踪状态变化
问题描述
我有 2 个组件:一个ParentComponent
呈现一个ChildComponent
父组件有一个ParentViewStore
,子组件有ChildViewStore
,
有没有办法在不使用生命周期方法(例如)的情况下跟踪ParentViewStore
属性更改?ChildViewStore
React.Component
ComponentWillReceiveProps()
示例代码:
class ParentViewStore{
@observable a;
}
class ChildViewStore{
/*
code to run when
ParentViewStore.a
changes
*/
}
构造函数内的代码ChildViewStore
只运行一次,后续的重新渲染不会再次触发构造函数。ParentViewStore
作为道具传递给ChildViewStore
我试过的:
class ChildViewStore{
@observable parentProperty;
constructor(props){
this.parentProperty = props.parentViewStore.parentProperty
observe(this.parentProperty, (change) => {
console.log("change")
});
}
}
但这会抛出[mobx] Cannot obtain administration from [parentPropertyValue]
解决方案
每次实例更改时,您都可以autorun
在构造函数中使用一个来运行一些自定义逻辑。ChildViewStore
a
ParentViewStore
例子
class ChildViewStore{
constructor(props){
autorun(() => {
console.log(`a changed: ${props.parentViewStore.a}`);
});
}
}
推荐阅读
- performance - UI5 性能参数:data-sap-ui-preload 与 data-sap-ui-async
- amazon-mws - 如何在亚马逊卖家中心创建沙盒账户
- spring - 从控制器返回的值的弹簧内部化
- java - Junit java.lang.OutOfMemoryError 超出 GC 开销限制
- java - onActivityResult 没有做任何事情
- javascript - 操作数组对象内的数据
- python - sklearn:随机删除多数类而不改组数据集
- java - Android 库线程安全
- ruby-on-rails - Rails 和主题森林集成问题,出现路由错误
- python - Python - 没有 qoutes 的数字列表