Redux를 사용하여 API에서 일부 데이터를 가져 오려고합니다. 내 코드는 다음과 같습니다Redux API에서 데이터 가져 오기
작업 :
// Import libraries
import axios from 'axios';
// Import types
import {
GET_ALL_PICKS
} from './types';
export const getAllPicks = ({ token }) => {
const getPicks = (dispatch) => {
axios({
method: 'get',
url: 'http://myapi/',
headers: {
Authorization: `Bearer ${token}`
}
})
.then((response) => {
console.log(response.data); // First log here returns data just fine
dispatch({
type: GET_ALL_PICKS,
payload: response.data
});
})
.catch((error) => {
console.log(error);
});
};
return getPicks;
};
감속기 :
// Import types
import {
GET_ALL_PICKS
} from '../actions/types';
// Set Initial State
const INITIAL_STATE = {
allPicks: {},
loading: false,
error: ''
};
// Make pick reducers
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case GET_ALL_PICKS:
return { ...state, allPicks: action.payload }; // Logging action.payload here returns data just fine
default:
return state;
}
};
구성 요소 : 나는 응용 프로그램을 실행하면
// Import Libraries
import React, { Component } from 'react';
import { Text } from 'react-native';
import { connect } from 'react-redux';
import {
getAllPicks
} from '../actions/picks';
// Make Component
class HomeScreen extends Component {
// Fetch Data
componentWillMount() {
const { token } = this.props;
this.props.getAllPicks({ token });
}
// Test response
componentDidMount() {
console.log(this.props.allPicks); // This log returns empty object, why?!
}
render() {
return (
<Text>Test</Text>
);
}
}
const mapStateToProps = ({ auth, picks }) => {
const { token } = auth;
const { allPicks } = picks;
return {
token,
allPicks
};
};
export default connect(mapStateToProps, { getAllPicks })(HomeScreen);
내가 작업 console.log
의 데이터를 참조 그리고 내가 감속기에서 console.log(action.payload)
을 실행하면 데이터가 잘 보이지만 구성 요소 I에서는 내 감속기에있는 데이터를 올바르게 연결하지 않는다는 것을 나타내는 빈 배열을 참조하십시오.
은 또한 일부 인터넷 검색 후 내 감속기에서 이것을 시도 :
return Object.assign({}, state, {
allPicks: action.payload
});
을하지만 다시 나는 같은 결과를 얻었다 여기에 로그의 스크린 샷이다. 누구든지 내가 잘못하고있는 것을 나에게 설명 할 수 있을까?