使用Redux传递数据,this.props仍然是空数组

时间:2017-08-09 16:51:37

标签: reactjs redux

我正在尝试使用Redux从操作中获取数据,并显示我从组件中获取的API数据中获取的JSON对象的属性。但是在遵循我在互联网上看到的所有步骤后,当我的组件中的console.log(this.props)时,我仍然得到一个空数组。这个空数组似乎每次使用时都会添加项目,每次都会向数组中添加“未定义”项。

哦,我的action.js

import 'whatwg-fetch';


export const FETCH_RECIPES = 'FETCH_RECIPES';
const ROOT_URL = 'http://myapi/recipe/id/';

export function fetchRecipes(id) {
    const url = ROOT_URL + id;
    return (dispatch) => {
    fetch(url)
        .then((response) => response.json())
        .then((request) => dispatch(fetchRecipesSuccess(request)))
    };
}

export function fetchRecipesSuccess(request) {
    return {
        type: FETCH_RECIPES,
        request
    };
}

和reducer我将我的动作导入reducer_recipes.js

import { FETCH_RECIPES } from "../actions/index";

export function recipes (state = [], action) {
    switch(action.type) {
        case FETCH_RECIPES:
            return [action.request.data, ...state];
        default:
            return state;
    }
}

我的createStore: const createStoreWithMiddleware = createStore(rootReducer, applyMiddleware(thunk));

Aaaaand最后,我的组件中的相关代码片段:

componentDidMount() {
    this.props.fetchData(1);
}

render() {
    return (
        <h1>{console.log(this.props)}</h1>
)}


function mapStateToProps(state) {
return { recipes: state.recipes };
}

const mapDispatchToProps = (dispatch) => {
    return {
        fetchData: (id) => dispatch(fetchRecipes(id))
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(Recipe);

我在哪里放弃与this.props的连接?几个小时以来一直在敲我的脑袋。

1 个答案:

答案 0 :(得分:0)

我无法看到API请求返回的数据,但我注意到了下面的一件事

当您访问该状态时,您将其作为具有数组属性,配方

的对象进行访问
function mapStateToProps(state) {
    return { recipes: state.recipes };
}

但是你要用[],

返回一个数组
import { FETCH_RECIPES } from "../actions/index";

export function recipes (state = [], action) {
    switch(action.type) {
        case FETCH_RECIPES:
            return [action.request.data, ...state];
        default:
            return state;
    }
}

也许你可以试试

return {...state, action.request.data};

return {...state, recipes: action.request.data};