【问题标题】:InfiniteLoader and react-reduxInfiniteLoader 和 react-redux
【发布时间】:2016-12-10 07:34:29
【问题描述】:

来自react-virtualised 的组件 InfiniteLoader 要求作为属性 loadMoreRows 传递的函数具有类似{ startIndex: number, stopIndex: number }): Promise 的签名。 我在我的项目中使用 redux,所以 loadMoreRows 是这样的 redux 动作创建者:

const fetchEntities(start, stop) {
  return fetch(`${myUrl}&start=${start}?stop=${stop}`)
}
const loadMoreRows = ({ startIndex, stopIndex }) => {
  return (dispatch, getState) => {
    return function(dispatch) {
      return fetchEntities(startIndex, stopIndex).then(
        items => dispatch(simpleAction(items)),
        error => console.log(error)
      )
    }
  }
}

之后,使用 react-redux 的 connect 函数将这个 action 连接到包含 InfiniteLoader 的 react 组件。

所以我不确定,我怎样才能满足签名要求,因为 redux 动作创建者不返回任何值/

【问题讨论】:

  • 我从 react-virtualised 的源代码中了解到,不需要从 loadMoreRows 函数返回 Promise。但是,如果您不这样做,您有义务调用 child.forceUpdate() 来更新底层组件。

标签: react-redux react-virtualized


【解决方案1】:

eyeinthebrick 是正确的。 Promise 不是必需的返回值。

当你“连接”一个 Redux action-creator 时,调用它(调度它)实际上会返回一个 Promise。因此,例如,我认为您可以做更多这样的事情......

function fetchEntities (start, stop) {
  return fetch(`${myUrl}&start=${start}?stop=${stop}`)
}

const loadMoreRows = ({ startIndex, stopIndex }) => {
  return async (dispatch, getState) => {
    try {
      const items = await fetchEntities(startIndex, stopIndex)
      await dispatch(simpleAction(items))
    } catch (error) {
      console.log(error)
    }
  }
}

此时InfiniteLoader 可以等待返回的 Redux 承诺。

【讨论】:

  • 现在无法检查,因为我还没有使用 es7。我目前的解决方案是通过对 ComponentWillRecieveProps 中下载项目的同情来手动更新。所以如果有新下载的项目,我会调用 ```virtualScroll.recomputeRowHeights()`。
  • 你不需要 ES7。您可以将 async/await 替换为普通的 Promise 链接,它应该仍然可以工作。 :)
  • Brian,我想你是在假设一些中间件的存在和使用,可能是 redux-thunk;开箱即用,AFAICT 调度只返回操作。
猜你喜欢
  • 2020-09-17
  • 2017-10-06
  • 2018-02-05
  • 2017-10-06
  • 1970-01-01
  • 2018-10-04
  • 2017-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多