gpt4 book ai didi

javascript - 重组 "withReducer": justification of async reducer function call

转载 作者:数据小太阳 更新时间:2023-10-29 06:05:14 24 4
gpt4 key购买 nike

我正在使用 withReducer HOC 并注意到这种行为:例如,在点击处理程序上调用它:

import React from 'react'
import { withReducer } from 'recompose'
import { compose } from 'ramda'

export default compose(
withReducer('state', 'dispatch', (state, { value }) => {
console.log(value)
return { ...state, value }
}, { value: 'zero' })
)((props) => {
const { dispatch, state } = props,
onClick = () => {
console.log('Hello')
dispatch({ value: 'one' })
dispatch({ value: 'two' })
dispatch({ value: 'three' })
console.log('World')
}
return (
<div>
<div>{state.value}</div>
<button onClick={onClick}>Click me</button>
</div>
)
})

它会产生

Hello

World

one

two

three

这意味着 reduce 函数是异步调用的。将其称为异步而不是立即将更改应用于存储的理由是什么?

最佳答案

reducer 是异步调用的,因为我们只能使用 setState 来更新树,而 setState 是异步的。

如果我们同步调用 reducer,我们需要将新状态保存在某处,然后调用 setState 并从保存位置异步获取新状态。最后,您的树仍然会异步更新。

这就是为什么recompose的withReducer()与redux略有不同的原因。你可以认为 withReducer 是 redux + react-redux 的 connect() 的简化版本。

关于javascript - 重组 "withReducer": justification of async reducer function call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41521459/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com