从API获取数据时使用反应生命周期的正确方法

问题描述 投票:0回答:1

我正在使用componentWillMount中的组件来调度redux操作

  componentWillMount() {
    this.props.fetchCoin()
    this.props.CurrencyRate()
  }

这将向Api发出请求并获取数据,这就是我的redux动作的相似之处

export const fetchCoin = () => {
  return function (dispatch) {
    console.log("here inside Dispatch")
    dispatch({type: CRYPTO_FETCHING}) 
    axios.get(ApiCoinCap).then((response) => {
      console.log("Response from Axios")
      console.log(response)
    return(
    dispatch({
      type: CRYPTO_FETCH_SUCESS,
      payload: response.data
    })
  )
  }).catch((error) => {
    console.log(error)
    return (
  dispatch({
      type: CRYPTO_DATA_FAIL,
      payload: error.data
    })
  )})

  }
}

我通过这样做加载这些数据

//Redux
const mapStateToProps = state => {
  return {
    cryptoLoaded: state.posts.itemsSucess,
    cryptoLoading: state.posts.itemsFetching,
    currencyLoaded: state.currency.DataSucess
  }
};

export default connect(mapStateToProps, {fetchCoin, updateCrypto, CurrencyRate})(cryptoTicker);

但是当我在componentDidMount中尝试在变量中提供值时,事实证明该对象未被加载

 componentDidMount() {
    this.socket = openSocket('https://coincap.io');
    var updateCoinData = [...this.props.cryptoLoaded];
      console.log("Crypto loaded redux test", this.props.cryptoLoaded)
      console.log("Update coin test", updateCoinData)
      this.socket.on('trades', (tradeMsg) => {

这可能是因为React生命周期方法是异步的?当它符合代码并达到这一点时,它还没有达到那一点?

[问题]我的上述理解是否正确?如果是的话,我怎么可能在var updateCoinData = [...this.props.cryptoLoaded];里面使用componentDidMount() {。一个选项可能可能是使用setTimeout但除此之外,我还能做什么?

你可以在这里看到完整的代码:https://github.com/irohitb/Crypto/blob/master/src/container/cryptoContainer.js

reactjs react-native redux react-redux
1个回答
0
投票

使用像redux-thunkredux-saga这样的redux中间件。

由于redux + react是异步的,如果你使用qzxswpoi和redux,你必须使用中间件

axios

https://github.com/reduxjs/redux-thunk

© www.soinside.com 2019 - 2024. All rights reserved.