【问题标题】:In React, what invokes returned function for things like higher order components and redux-thunk?在 React 中,什么会为高阶组件和 redux-thunk 之类的东西调用返回函数?
【发布时间】:2020-04-01 00:41:22
【问题描述】:

我的问题是关于什么调用 React 中的返回函数?例如使用 redux-thunk,假设我从任意组件的 componentDidMount() 调用以下函数,

getCurrentPoll() 

我的 redux-thunk 动作定义如下:

export const getCurrentPoll = pollId => async dispatch => {
    try {
        const currentPoll = await api.call('get', `polls/${pollId}`)
        dispatch(actionGetCurrentPoll(currentPoll))
        dispatch(removeError())
    } catch (err) {
        const { message } = err.response.data
        dispatch(addError(message))
    }
}

我的理解是调用getCurrentPoll()会返回异步调度函数。但是什么调用了返回的异步调度函数呢?

对于高阶组件也是如此。比如下面的函数,它将上下文 api 值注入到组件 props 中。

const withRoomConsumer = Component => props =>
    <RoomContext.Consumer>
        {value => <Component {...props} context={value} />}
    </RoomContext.Consumer>

当你运行export default withRoomConsumer(RoomsContainer)时,调用返回函数props =&gt;...

提前谢谢你

【问题讨论】:

  • 对于 redux-thunk 示例,这是由 redux-thunk 中间件处理的 - 请参阅 redux.js.org/advanced/middleware 以很好地解释中间件的动机和实现以及非常简单的 thunk 中间件的实现结束。

标签: javascript reactjs redux react-context


【解决方案1】:

redux-thunk 创建一个 redux 中间件并检查该操作是否是一个函数,然后调用该函数。你可以查看他们的implementation here,很简单只有14行

React HOC 返回一个功能性的 React 组件,React 将照常渲染该组件。 (也可以是类组件)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 2018-05-21
    • 1970-01-01
    • 2020-12-19
    • 2023-02-07
    相关资源
    最近更新 更多