[英]MobX state tree - array of models doesn't trigger update
I have following model: 我有以下模型:
const AnotherModel = types.model({
foo: types.string
});
export const SomeCollectionModel = types
.model({
data: types.array(AnotherModel),
})
.views((self) => ({
getData: () => self.data,
}))
.actions((self) => ({
fetchData: flow(function* fetchData() {
try {
const data =
yield service.fetchData();
self.data.replace(
data.map((f) => AnotherModel.create(f)),
// Using plain json instead of create does the same
);
} catch (err) {
console.error(err);
}
})
}));
Then I have two React components, which I compose with inject
and observer
. 然后,我有两个React组件,分别由
inject
和observer
。
Parent one (view/page): 父级之一(视图/页面):
compose(
inject((states) => ({
fetchData: () =>
states.myModel.fetchData(),
})),
observer,
)
Child one: 孩子一:
compose(
inject(states => ({
data: states.myModel.getData()
})),
observer
)
I have a re-rednering problem. 我有一个重新调整的问题。 Initially child component doesn't render anything.
最初,子组件不呈现任何内容。 In the meantime data is fetched (action triggers itself).
同时,将获取数据(动作触发自身)。 However data is not updated in child.
但是,数据不会在子级中更新。
componentWillReact
doesnt trigger. componentWillReact
不会触发。 After changing routes (rerender by router) view gets updated 更改路由(通过路由器渲染)后,视图将更新
Do you have any idea? 你有什么主意吗? I'm stuck for hours.
我被困了几个小时。
inject(states => ({
data: states.myModel.data
}))
observer
if you use inject
. inject
则无需使用observer
。 MyComponent will observe what's inside the inject just fine: inject(states => ({
data: states.myModel.data
}))(MyComponent)
inject(states => ({
data: states.myModel.data,
length: states.myModel.data.length
}))(MyComponent)
inject(states => ({
data: states.myModel.data,
length: states.myModel.data.length
}))(MyComponent)
const MyComponent = ({ data }) => (
<div>{data.map(item => (
<MyDataItem item={item} />
))}
</div>
)
inject((states, props) => ({
foo: props.item.foo
}))(MyDataItem)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.