2016-10-13 3 views
0

Axis를 사용하여 AJAX 호출을하고 데이터가 정의되지 않은 상태로 반환 된 다음 몇 초 후에 배열을 조작합니다. 나는 componentDidMount와 componentWillMount를 시도했다. 나는 초기 상태를 가진 생성자를 소품으로 만들려고 시도했다. React.createClass를 사용하지 않는 한 getInitial 상태는 사용되지 않습니다.반응 ajax 호출이 처음에 정의되지 않았습니다.

여기 내 코드가 있습니다.

행동 /하는 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; 
    } 
} 

당신은 비동기 작업을 & thunk- 가져올 필요를 사용할 필요가

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); 

답변

0

코드가 잘못되어 발생한 문제가 아닙니다. 당신이 바로하고있는 것처럼 보입니다.

문제는 앱이 존재하며 모든 데이터가 준비되기 전에 표시된다는 것입니다. 액시 얼 호출은 완료하는 데 오랜 시간이 걸립니다. 완료 될 때까지 앱은 사용자가 좋아하든 없든 사용자에게 무언가를 보여줍니다.

따라서 시작과 데이터 도착 사이에 strainsundefined이 될 것입니다. 기다리는 동안 사용자에게 무엇을 표시할지 결정해야합니다. 일반적인 솔루션은 회 전자입니다.

0

app.js 미들웨어 중 하나를 선택합니다.

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)); 

} 
} 
관련 문제