我该如何使用新获取的数据来重新呈现组件?
我需要实现的是基于所选模型获取数据。
例如考虑一下
const data1 = [
{
name: 'asd',
id: '3'
},
{
name: 'aa',
id: '4'
}
]
const data2 = [
{
name: 'sadasqw1212',
id: '1'
},
{
name: 'asokdos1111',
id: '2'
}
]
const MODEL = types.model({
name: types.optional(types.string, ''),
id: types.identifier
})
const testStore = types.model({
searchResults: types.optional(types.maybe(types.array(MODEL)), []),
selected: types.maybe(types.reference(MODEL))
})
.actions(self => ({
fetch(id) {
const dat1 = data1.map((item) => MODEL.create(item))
const dat2 = data2.map((item) => MODEL.create(item))
self.searchResults = id === 1 ? dat1 : dat2
},
setSelected(item) {
self.selected = item
}
}))
const App = inject('store')(observer(({store}) => {
return (
<div>
<button onClick={() => store.fetch(1)}> 1</button>
<button onClick={() => store.fetch(2)}> 2</button>
{store.searchResults.map((item) => (
<button onClick={() => store.setSelected(item)}>SET ({item.id} - {item.name})</button>
))}
<br/>
<br/>
{store.selected &&<div>
SELECTED
{store.selected.id}
<br/>
{store.selected.name}
</div>}
</div>
)
}));
const store = testStore.create();
console.log(store)
render(<Provider store={store}>
<App/>
</Provider>, document.getElementById("root"));