我有以下模型:
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);
}
})
}));
然后我有两个React组件,分别由inject
和observer
组成。
父母一(视图/页面):
compose(
inject((states) => ({
fetchData: () =>
states.myModel.fetchData(),
})),
observer,
)
一个孩子:
compose(
inject(states => ({
data: states.myModel.getData()
})),
observer
)
我有一个重新调整的问题。最初,子组件不呈现任何内容。同时,将获取数据(动作触发自身)。但是,数据不会在子级中更新。 componentWillReact
不会触发。
更改路由(通过路由器渲染)后,视图会更新
你有什么主意吗?我被困了几个小时。
答案 0 :(得分:1)
inject(states => ({
data: states.myModel.data
}))
observer
,则无需使用inject
。 MyComponent会很好地观察注入中的内容: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)