应用程序的状态不会通过 React、MobX 中的 props 在代码中立即更新
如果我有这样的代码
<button onClick = {()=>{
store.increment()
console.log(store.count)
}
}>{store.count}</button>
那么当您单击按钮时,计数器将被更新,并且计数器将已经在控制台中更新。 但是,如果您创建一个将接受数量和回调的计数器组件,则状态将是异步的
<Counter count = {store.count} increment = {store.increment}/>
我如何确保控制台中的状态已更新。如果可能的话,没有 didUpdate 方法和更新钩
codesandbox https://codesandbox.io/s/mobx-counter-example-forked-v3qcrw?file=/src/index.js
If I have such a code
<button onClick = {()=>{
store.increment()
console.log(store.count)
}
}>{store.count}</button>
Then when you click on the button, the counter will be updated, and the counter will already be updated in the console.
But if you create a Counter component that will accept the quantity and callback, the state will be asynchronous
<Counter count = {store.count} increment = {store.increment}/>
How can I make sure that the state in the console is already updated. Without the didUpdate method and the update hook if possible
codesandbox https://codesandbox.io/s/mobx-counter-example-forked-v3qcrw?file=/src/index.js
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先:不要使用过时的库版本。将它们更新到最新。
第二:将
observable
api 更改为makeAutoObservable
,删除额外的actions
。第三:将每个使用可观察值的组件包装到observer HOC 中。在您的示例中,您包装了
Counter
,但 Counter 实际上不使用任何可观察值,它仅获取appState.count
作为道具,当您引用它时,它将是一个原始值。然后你将 Counter 直接传递给 ReactDOM.render,这是行不通的。我用
App
组件包装了它:这是 Codesandbox 包含工作代码
First of all: don't use outdated library versions. Update them to latest.
Second: change
observable
api tomakeAutoObservable
, remove extraactions
.And third: wrap every component that uses observable values into
observer
HOC. In your example you wrappedCounter
, but Counter actually does not use any observable values, it only getsappState.count
as a prop which will be a primitive value when you reference it. And then you pass Counter directly to ReactDOM.render, that won't work.I've wrapped it with
App
component:Here is Codesandbox with working code