我在使用包时遇到 setState 问题:reactn
当我替换these lines (1)时与 those lines (2) ,代码有效。 (2) 是一种解决方法,处理异步 setState,但我想了解为什么 (1) 不起作用。
据我所知,我可以将回调函数传递给 React Hooks 中的 setSomeState
:
If the new state is computed using the previous state, you can pass a function to
setState
This也是 reactn
文档中 useGlobal
的另一种用法,它还使用回调函数作为 setGlobal 的参数。为什么他们的示例有效但我的示例无效?
完整代码: https://snack.expo.io/@loia5tqd001/d26e8f
片段:
listSymbols = [ "USD", "EUR", ... ]
usdRates = {} // expect to be usdRates = { USD: 1, EUR: 0.9 ... }
// getExchangeRate is in utils/utils.js
// => The code doesn't work
for (const symbol of listSymbols) {
getExchangeRate("USD", symbol).then(exchangeRate => {
setUsdRates(oldUsdRates => ({
...oldUsdRates,
[symbol]: exchangeRate
}))
.then(() => console.log("Call api getting exchange rate for " + symbol, usdRates) )
})
}
// => The code works as expected
for (const symbol of listSymbols) {
getExchangeRate("USD", symbol).then(exchangeRate => {
usdRates[symbol] = exchangeRate
console.log("Call api got exchange rate for " + symbol, usdRates)
})
}
setUsdRates(usdRates)
最佳答案
根据reactn的来源,使用useGlobal('propertyName')
版本的钩子(Hook)时,似乎不支持更新程序函数样式。
以下是属性 setter 的定义:https://github.com/CharlesStover/reactn/blob/master/src/use-global.ts#L95
您可以看到它创建了一个 newGlobalState
对象并将其传递给 setGlobal
。
然后setGlobal
在全局状态管理器上调用set
:https://github.com/CharlesStover/reactn/blob/master/src/global-state-manager.ts#L302
由于属性 setter 中的 newGlobalState
始终是一个对象,因此永远不会使用更新程序版本。
您可以通过不向 useGlobal
传递任何内容并处理整个状态对象来实现您想要的目标,如您链接的文档中的示例所示:
const [global, setGlobal] = useGlobal();
...
getExchangeRate("USD", symbol).then(exchangeRate => {
setGlobal(oldGlobal => ({
...oldGlobal,
usdRates: {
...oldGlobal.usdRates,
[symbol]: exchangeRate,
},
}))
.then(() => console.log("Call api getting exchange rate for " + symbol, usdRates) )
})
}
此外,我不确定您的其他示例是否 100% 正确 - 您不会等到所有异步 getExchangeRate
调用完成后才调用 setUsdRates
。
关于javascript - setState 与reactn 同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58334053/