【问题标题】:Wait for AJAX request ( React, Redux)等待 AJAX 请求(React、Redux)
【发布时间】:2017-06-12 05:55:46
【问题描述】:

AJAX调用完成后需要显示数据。

我的减速机:

import { INCOME_PROFILE } from '../actionTypes'
import Immutable from 'immutable'

const initialUserState = [];
const profileReducer = function(state = initialUserState, action) {
   //console.log('actiondata in reducer:' + action.data + action.type);

  switch(action.type) {

    case 'INCOME_PROFILE_IS_LOADING': 
     return Object.assign({}, state, {  hh: action.hasFetched });

  case 'INCOME_PROFILE': 
         return Object.assign({}, state, { course_list: action.data, hh: action.hasFetched });

  default: 

  return state;
  }
}
export default profileReducer

我的动作创建者:

export function GET_ITEM_REQUEST() {
  return {
    type: INCOME_PROFILE_IS_LOADING,
    hasFetched: false,
  }
}



function receiveData(json) {
    return{

        type: INCOME_PROFILE,
        data: json,
        hasFetched: true
    }
};

export function IncomeProfileList () {

    return dispatch => {

        return (

            axios.post(Api.getURI("profile"),{}, {
      headers: { 'X-Authenticated-Userid': '15000500000@1' }
     }).then(function (response) {


                //console.log(response.data);
                dispatch(receiveData(response.data.body));

            })
        .catch((error) => {
                console.log(error);
            })
            )
    }
}

我的组件:

class IncomeProfile extends Component {
  constructor(props) {
    super(props)
  }

  componentDidMount() {
    this.props.IncomeListProfile();
      }

render() {
console.log(this.props.isloading);

if (this.props.isloading) {
            return <p>Sorry! There was an error loading the items</p>;
        }
}
}
const mapDispatchToProps = function(dispatch) {
  return {
      IncomeListProfile: () => dispatch(IncomeProfileList())
      }
  }

const mapStateToProps = function(state) {
  //var mystore = state.toJS()
  var mystore = state.getIn(['incomeProfileList'])['course_list'];
  var mystored = state.getIn(['incomeProfileList']);
  console.log(mystored.hh);
  var copy = Object.assign({}, mystore);
  return {
    items: copy.course_list,
    isloading: mystored.hh
        };

}

我需要下一个:虽然响应没有完成,但我不需要显示数据。条件如果现在不工作

console.log 第一次得到未定义 - 认为一定是假的,但它没有声明为假。第二次它变成了真的。

【问题讨论】:

    标签: javascript jquery ajax reactjs redux


    【解决方案1】:

    您不需要属性 'isLoading' - 只需处理 2 种情况,其中您有数据而没有数据。将此条件放在 render() 函数中,因为组件在通过 reducer 传递数据后会刷新。在您的情况下,语法将是这样的:

      render() {
        if(!this.props.items) {
          return <div>Loading...</div>;
        } else {
          return (
            <div>Display your data!</div>
          ); 
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2018-08-05
      • 1970-01-01
      • 2015-02-21
      • 2014-04-24
      • 1970-01-01
      • 2017-06-09
      • 2017-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多