【问题标题】:Redux not updating right after dispatch in functional componentsRedux 在功能组件中调度后没有立即更新
【发布时间】:2021-09-16 14:49:14
【问题描述】:

最近我决定将我的代码从类更改为功能组件。我正在使用 redux、axios 和 axiosMiddleware。自从我开始改用功能组件后,我发现了一些奇怪的东西。请参阅以下示例,该示例是使用调度的请求(我正在使用 connect 和 mapDispatchToProps):

const getUserActivity = () => {
 await props
      .get(displayDateString)
      .then((response) => {
        console.log(response); //prints response
        console.log(props.activity); //prints part of the redux that should be updated
      })
      .catch((error) => console.log('error ' + error));
}
const mapDispatchToProps = (dispatch) => ({
  get: (date) => dispatch(ActivityReportActions.get(date))
})

我的问题是,当我在“then”之后得到响应时,redux 不会立即更新,只是之后。 “console.log(props.activity)” 打印之前的状态,在某些情况下,我更喜欢在响应之后立即访问 redux。有谁知道为什么这发生在功能组件而不是类组件中?如果是,是否有不需要使用 useEffect() 的解决方案?

谢谢!

【问题讨论】:

    标签: javascript reactjs react-native redux


    【解决方案1】:

    在分发后立即从 props 中读取 new 值是不可能的。 React 还没有机会重新渲染。

    如果您需要在调度后立即读取最新状态,则必须将逻辑编写为 thunk,它可以访问 getState

    https://redux.js.org/usage/writing-logic-thunks#accessing-state

    【讨论】:

    • 谢谢你是对的,使用 thunk 是一个很好的解决方案。我想我将使用来自请求的响应,而不是立即访问 redux,并将 redux 仅用于视图更新。尽管如此,出于某种原因,这在类组件中起作用还是很奇怪。
    猜你喜欢
    • 2020-04-16
    • 2019-11-15
    • 2018-12-30
    • 2017-05-06
    • 2020-04-25
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    相关资源
    最近更新 更多