如何替换引用的Mobex状态树数组

时间:2018-11-20 17:16:07

标签: reactjs mobx mobx-react mobx-state-tree

我该如何使用新获取的数据来重新呈现组件?

我需要实现的是基于所选模型获取数据。

例如考虑一下

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"));

我一直收到这个错误,该错误现在像7个小时一样阻塞了我。...有人可以指出我用新数据完成这种表替换的正确方法吗? enter image description here

0 个答案:

没有答案