【问题标题】:React-Redux - using a response from a fetch request in componentDidMount in another request in the componentReact-Redux - 在组件中的另一个请求中使用来自 componentDidMount 中的获取请求的响应
【发布时间】:2023-03-23 05:15:02
【问题描述】:

我有一个组件在 componentDidMount 上触发 fetch 请求(在 redux 中)。在同一个组件中,我需要使用第一个响应数据触发另一个 redux 获取请求,最好是在渲染之前。

由于在 redux 操作中执行 fetch,我无法使用 componentDidMount 中的 promise 来执行此操作,因为当操作开始但未完成时,promise 会解析。

在研究中,我认为它可能可以使用 componentWillRecieveProps 来完成,但是我不完全理解如何并且还了解到这个钩子很快就会被贬值。

任何帮助将不胜感激。

第一个动作:

componentDidMount(){    
 this.props.onGetSessionId(this.parseToken(this.props.location.search))
};

第二个动作:

this.props.onFetchFavourites(this.props.sessionId)

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

    如果没有看到onGetSessionIdonFetchFavourites 是如何实现的代码,这里很难提供帮助,但假设您使用的是redux-thunk,它可能是这样的:

    function getSessionId(token) {
      return function (dispatch) {
        return fetchSessionId(token)
        .then(
          response => dispatch(getSessionIdSuccess(forPerson, response.id))
        )
        .catch(
          error => dispatch(getSessionIdFailure(error)
        )
      };
    }
    
    function getFavorites(sessionId) {
      return function (dispatch) {
        return fetchFavorites(sessionId)
        .then(
          response => dispatch(getFavoritesSuccess(sessionId, response.favorites))
        )
        .catch(
          error => dispatch(getFavoritesFailure(error)
        )
      };
    }
    

    fetch 返回一个promise,因此您可以继续链接.then 并使用前一个then 的返回值。这可以让你做类似的事情

    function getSessionIdAndFavorites(token) {
      return function (dispatch) {
        return fetchSessionId()
        .then(
          response => {
            dispatch(getSessionIdSuccess(response.id))
            return response.id
          }
        )
        .then(id => {dispatch(getFavorites(id)}
        .catch(
          error => dispatch(getSessionAndFavoritesIdFailure(error)
        )
      };
    }
    

    【讨论】:

      【解决方案2】:

      onGetSessionId你可以返回promise,像这样:

      function onGetSessionId(param) {
          return new Promise((resolve, reject) => {
              apiClient.call()
                  .then(data => {
                      resolve(data);
                  })
                  .catch(error => {
                      reject(error)
                  })
          })
      }
      

      然后在componentDidMount:

      componentDidMount(){
          this.props.onGetSessionId(this.parseToken(this.props.location.search))
              .then(data => {
                  // ... do stuff with returned data
              })
      }
      

      【讨论】:

        猜你喜欢
        • 2020-03-14
        • 2014-07-24
        • 2019-09-19
        • 1970-01-01
        • 1970-01-01
        • 2019-08-10
        • 2016-11-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多