我对react和mobx有问题。
每1秒执行一次代码分派操作,分派之后什么也没有发生。
这是我的代码:
import React from 'react';
import { action, observable } from "mobx"
import { observer } from "mobx-react"
const COLORS = [
'blue',
'yellow',
'brown',
'green'
]
const nextColor = (key) => {
if (key !== undefined && key + 1 < COLORS.length) {
return key + 1
}
return 0
}
const store = observable({
circles: observable.map({}),
getColorId(name) {
return store.circles.get(name)
},
update: action(function update(name) {
store.circles.set(name, nextColor(store.getColorId(name)))
})
})
const OX = 100
function AppMobX() {
const circles = []
for (let i = 0; i < OX; i++) {
circles.push(<CircleContainer key={i} name={i}/>)
}
setInterval(() => {
store.update(Math.ceil(Math.random() * OX))
}, 1000)
return (
<div className="app">
{circles}
</div>
);
}
const Circle = ({colorId}) => {
return <div style={{ backgroundColor: COLORS[colorId] }} className="circle"/>
}
const CircleContainer = observer((name) => {
return <Circle colorId={store.getColorId(name)}/>
})
export default AppMobX;