Redux不会从API请求中获取数据

时间:2019-06-20 01:21:53

标签: reactjs api redux react-redux

我是React / Redux的新手。我正在使用API​​制作应用程序,但是代码不起作用。当我运行代码时,它说“ this.props.recipes.map不是函数”,并且不呈现任何内容。

如果我将有效负载更改为:“有效负载:response.data.recipes”,则错误更改为“给定动作“ FETCH_RECIPE”,减速器“ recipes”返回未定义”。但屏幕上没有错误(仅在控制台中)。我以为编写“((state = [],action)”)可以解决问题,但似乎没有。有什么问题,我该如何解决该错误?

Action Creator

import recipe from '../apis/recipe';

export const fetchRecipe = () => async dispatch => {
    const response = await recipe.get('');

    dispatch({ type: 'FETCH_RECIPE', payload: response.data })
};
Reducer

import { combineReducers } from 'redux';

const recipeReducer = (state = [], action) => {
    switch(action.type) {
        case 'FETCH_RECIPE':
            return action.payload;
        default:
            return state;
    }
};

export default combineReducers({
    recipes: recipeReducer
});
import React from 'react';
import { connect } from 'react-redux';
import { fetchRecipe } from '../actions';

class Recipe extends React.Component {
    componentDidMount() {
        this.props.fetchRecipe();
        console.log("This doesn't work", this.props.recipes)
    }

    renderList() {
        return this.props.recipes.map(recipe => {
            return (
                <div>
                    <p>{recipe.publisher}</p>
                </div>
            )
        })
    }

    render() {
        console.log("First loaded: empty, second time: data fetched", this.props.recipes)
        return (
            <div>
                {this.renderList()}
            </div>
        );
    }
}

const mapStateToProps = (state) => {
    return { recipes: state.recipes }
};

export default connect(mapStateToProps,{
    fetchRecipe
})(Recipe);
API Request

import axios from 'axios';
import { key } from './config';

export default axios.create({
    baseURL: `https://cors-anywhere.herokuapp.com/https://www.food2fork.com/api/search?key=${key}&q=pizza`
});

0 个答案:

没有答案