在 redux+react web 应用程序中,如何知道一个异步操作最终被分派到状态

In redux+react web app, how to know one async action is finally dispatched to state

Rudx-thunk 在分派异步操作方面做得很好,它最终会修改异步操作中获取的状态。但是我怎么知道它最终修改获取的 redux 状态的时刻?

在我的例子中,我想从服务器读取配置,因为有些组件需要这些配置,所以我必须在获取配置后呈现整个应用程序。但到目前为止,我无法通过使用 redux-thunk 或任何其他 redux 异步中间件来解决问题。

更新 #1 显示一些代码以更好地表达我自己。

// reducer
(state, action) => Object.assign({}, state, {config: action.config});

// action creator
const fetchConfig = () => (dispatch) => {
    fetch('http://server.com/...')
    .then(config=>dispatch({type: 'LOAD_CONFIG', config}))
}

// connect reducer to state
createStore({config: configReducer})

// render
import { render } from 'react-dom';
render (<App><News /></App>)

// some component consume state.config
@connect(state=>{config: state.config})
const News = props=>(
    <div>
        {(props.config === '...')? <div>...</div> : <div>...</div>}
    </div>
)

上面看起来不错,但是由于操作可能需要时间并在组件首次渲染后更新状态,因此组件可能会显示意外结果。我真正想做的是(我只记下render部分,其他的应该一样):

// render
loadConfigFinished
.then(()=> render((<App><News /></App>)))

// render
on('loadConfigFinished', ()=> render((<App><News /></App>)));

应该是第2种吧,怕不是redux-y。

无论如何,以上只是一个示例,显示有时我们确实需要在某些动作最终分派到 redux 状态时得到通知。

export function readConfig() {
  return (dispatch) => {
    dispatch(readingConfig());

    someAsyncFunction((error, result) => {
      if (!error) {
        dispatch(readConfigSuccess(result));
      } else {
        dispatch(readConfigFail(error));
      }
    });
  }
}

当然,readConfigSuccessreadConfigFailreadingConfig 是 return 动作对象的动作创建器函数,例如:

export const READING_CONFIG = 'READING_CONFIG';
export function readingConfig() {
  return {
    type: READING_CONFIG,
  }
}

当您的减速器处理 readConfigSuccess 操作时,它们会更新 redux 状态。

应用程序会使用所有状态更改的更新道具重新呈现,因此此特定操作没有什么特别之处。

除了通常只有一小部分状态发生变化并且重新渲染看起来很像以前的渲染,在这里我希望相对大部分的状态会被缩减器改变这个特定的动作和重新呈现将呈现一个变化很大的应用程序。

不过你不用担心,它应该可以正常工作。

或者您还有其他意思,您是否希望通过检索配置执行更多异步工作?

查看您的代码,我发现您的问题很简单:我什么时候呈现依赖于服务器数据的组件,同时等待该数据,而不将 undefined 传递到我的组件中?

我会有一个连接到配置状态的容器组件,并有条件地呈现需要它的组件,或者一个加载模板:

const Container = props => {
  if (props.config) {
    return <ConfiguredComponent config={props.config} />
  } else {
    return <Loading />
  }
}