最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Recompose "withReducer": justification of async reducer function call - Stack Overflow

programmeradmin0浏览0评论

I'm using withReducer HOC and noticed this behaviour: Calling this on click handler for example:

import React from 'react'
import { withReducer } from 'repose'
import { pose } from 'ramda'

export default pose(
  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>
  )
})

I'm using withReducer HOC and noticed this behaviour: Calling this on click handler for example:

import React from 'react'
import { withReducer } from 'repose'
import { pose } from 'ramda'

export default pose(
  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>
  )
})

It will produce

Hello

World

one

two

three

This means that reduce function is called asynchronously. What is justification for calling it async rather than applying changes to store right away?

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Jan 7, 2017 at 12:31 KomlevKomlev 512 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

The reducer is called asynchronously because we can only use setState to update the tree and setState is asynchronous.

If we call the reducer synchronously, we will need to save the new state somewhere, then call setState and get the new state asynchronously from where we save it. In the end, your tree still get updated asynchronously.

This is why repose's withReducer() is slightly different from redux. You can think of that withReducer is a simplified version of redux + react-redux's connect().

In this case, dispatch is actually a wrapper for the vanilla API method setState.

React implements setState asynchronously because state transitions are sometimes batched together for performance reasons.

According to the React docs:

setState() does not immediately mutate this.state but creates a pending state transition....There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

发布评论

评论列表(0)

  1. 暂无评论