在react中使用Mobx问题总结

2,161 阅读1分钟

observer的组件,只有当前组件render方法中直接使用的数据才会被追踪

例如

@observer
const MyComponent = ({todo})=>
    <SomeContainer 
    title = {()=><div>{todo.title}</div>} />

看似todo.title是在MyComponent组件中使用的,但不是直接使用的,因为回调函数的执行是在SomeContainer中,回调函数title执行时,todo.title才是直接使用的,要想让SomeContainer可以正确响应todo.title的变化,SomeContainer本身也需要observer包装

@observer
const MyComponent = ({todo})=>
    <SomeContainer 
    title = {()=>observer(({todo})=><div>{todo.title}</div>)} />

还有另外一种方法是使用mobx-react提供的Observer组件

@observer
const MyComponent = ({todo})=>
    <SomeContainer 
    title = {<Observer><div>{todo.title}</div></Observer>} />

mobx只追踪同步执行过程中的数据

var todo = observable({title: work});
autorun(()=>{
    setTimeout(()=>{console.log(todo.title)},100);
})

autorun没有响应 autorun在执行期间没有访问到任何可观测对象,,todo.title是在计时器异步执行期间访问的

自动运行程序when仅会执行一次

when(predicate: () => boolean, effect?: () => void, options?)

predicate会自动响应它使用的任何state的变化,当返回true时,才会触发effect函数的执行,然后 autorunner(自动运行程序) 会被清理,所以effect只会执行一次。when函数返回一个清理器以提前取消自动运行程序。