应用程序的状态不会通过 React、MobX 中的 props 在代码中立即更新

发布于 2025-01-09 21:23:59 字数 589 浏览 2 评论 0原文

如果我有这样的代码

<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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜心小果奶 2025-01-16 21:23:59

首先:不要使用过时的库版本。将它们更新到最新。

第二:将 observable api 更改为 makeAutoObservable,删除额外的 actions

第三:将每个使用可观察值的组件包装到observer HOC 中。在您的示例中,您包装了 Counter,但 Counter 实际上不使用任何可观察值,它仅获取 appState.count 作为道具,当您引用它时,它将是一个原始值。然后你将 Counter 直接传递给 ReactDOM.render,这是行不通的。

我用 App 组件包装了它:

const App = observer(() => {
  return <Counter count={appState.count} increment={appState.incCounter} />;
});

这是 Codesandbox 包含工作代码

First of all: don't use outdated library versions. Update them to latest.

Second: change observable api to makeAutoObservable, remove extra actions.

And third: wrap every component that uses observable values into observer HOC. In your example you wrapped Counter, but Counter actually does not use any observable values, it only gets appState.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:

const App = observer(() => {
  return <Counter count={appState.count} increment={appState.incCounter} />;
});

Here is Codesandbox with working code

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文