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