反应ajax调用最初是未定义的

时间:2016-10-13 23:50:28

标签: javascript reactjs redux react-redux axios

我正在使用Axios进行AJAX调用,数据返回undefined,然后在几秒钟后调用数组。我已经尝试过componentDidMount和componentWillMount。我试过用一个初始状态作为道具的构造函数。除非使用React.createClass,否则不推荐使用getInitial状态。

这是我的代码,任何有用的东西!

动作/ index.js

import axios from 'axios';
import { FETCH_STRAINS } from './types';
const ROOT_URL = `https://www.cannabisreports.com/api/v1.0/strains?sort=name&page=3`;

export function fetchStrains() {
    return dispatch => {
        axios.get(ROOT_URL)
             .then(response => {
                dispatch({
                    type: FETCH_STRAINS,
                    payload: response.data.data
                })
             })
             .catch( error => console.log(error));
    }
}

减速器/ index.js

import { FETCH_STRAINS } from '../actions/types';
import initialState from './initialState';
export default function(state = initialState.strains, action) {
    switch(action.type) {
        case FETCH_STRAINS:
            return { ...state, strains: action.payload };
        default: 
            return state;
    }
}

app.js

import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from './actions';
import './App.css';

class App extends Component {
  componentWillMount() {
       this.props.fetchStrains();   
  }

  render() {
    return (
      <div className="App">

         {this.props.strains === undefined ? console.log("this is undefined") : console.log(this.props.strains)}

      </div>
    );
  }
}

function mapStateToProps( state ) {
    return { strains: state.strains.strains }
}

export default connect(mapStateToProps, actions)(App);

2 个答案:

答案 0 :(得分:0)

您需要使用异步操作&amp;需要在组合减压器的同时导入thunk-middleware。

export function fetchStrains() {

// Thunk middleware knows how to handle functions.
// It passes the dispatch method as an argument to the function,
// thus making it able to dispatch actions itself.

return function (dispatch) {

// First dispatch: the app state is updated to inform
// that the API call is starting.

// The function called by the thunk middleware can return a value,
// that is passed on as the return value of the dispatch method.

// In this case, we return a promise to wait for.
// This is not required by thunk middleware, but it is convenient for us.

 axios.get(ROOT_URL)
         .then(response => {
            dispatch({
                type: FETCH_STRAINS,
                payload: response.data.data
            })
         })
         .catch( error => console.log(error));

 }
}

答案 1 :(得分:0)

您面临的问题不是因为您的代码错误。从快速浏览一下,看起来你做得对。

问题是您的应用程序存在并且在您准备好所有数据之前显示。 axios调用需要很长时间才能完成。在完成之前,无论您是否喜欢,您的应用都会向用户展示一些内容。

因此,在启动和数据到达之间,strains将是undefined。您必须决定在等待时向用户显示的内容。一个常见的解决方案是旋转器。