Redux动作调用返回undefined然后定义

时间:2017-10-16 02:53:30

标签: reactjs redux redux-thunk

目前正在开展react redux项目。

我能够调用我的动作fetchProjects()来处理对服务器的axios get请求。

我的代码问题在于,在使用我的项目列表填充状态之前,它将日志控制为未定义。

我的目标是在调用render函数时在屏幕上呈现我的项目列表。但是当我调用this.props.projects时,组件崩溃,因为它呈现未定义。

以下是调用fetchProjects操作的组件。



import React, { Component } from 'react';
import Searchbar from '../../vp-ui/vp-searchbar/vp-searchbar.component.js';
import { connect } from 'react-redux';
import * as actions from '../../vp-services/projects/actions';
require('./vp-genecart.component.scss');

class GeneCart extends Component {

    constructor(props) {
        super(props);
        this.state        = { projects: [] };
        this.props.fetchProjects();
    }

    render() {
        console.log("h1", this.props.projects);
        return (
            <div>
                hello
            </div>
        )
    }
}

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

export default connect(mapStateToProps, actions)(GeneCart)
&#13;
&#13;
&#13;

以下是执行get请求的操作

&#13;
&#13;
import axios from 'axios';
import history from '../../history';
import instance from '../instance';
import {
    PROJECTS_FETCH,
    PROJECTS_ERROR
} from './types';

export function fetchProjects() {
    return function(dispatch) {
        instance.get(
            `api/projects/`,
            {
                withCredentials: true
            }
        ).then((response) => {
                var projects = response.data.results;
                dispatch({
                    type: PROJECTS_FETCH,
                    payload: projects
                });
            })
            .catch((error) => {
                dispatch(projectsError('Couldn\'t get projects'));
            });
    }
}
&#13;
&#13;
&#13;

这是减速器

&#13;
&#13;
import {
    PROJECTS_FETCH,
    PROJECTS_ERROR
} from './types';

export default function(state={}, action) {
    switch(action.type) {
        case PROJECTS_FETCH:
            return { ...state, projects: action.payload };
        case PROJECTS_ERROR:
            return { ...state, error: action.payload };
    }

    return state;
}
&#13;
&#13;
&#13;

这是它在我的屏幕上显示的方式 enter image description here

1 个答案:

答案 0 :(得分:1)

问题是,在获取数据之前,redux存储区中的projects确实是undefined。因此,如果projects应该返回一个数组,则应该将它设置为初始状态的空数组。

const initialState = {
    projects: []
};

export default function(state = initialState, action) {
    switch(action.type) {
        case PROJECTS_FETCH:
            return { ...state, projects: action.payload };
        case PROJECTS_ERROR:
            return { ...state, error: action.payload };
    }

    return state;
}

编辑:阅读评论,我认为您想要做的事情更可能是这样的:

减速器

const initialState = {
    projects: null
};

成分

render() {
    if (this.props.projects === null) return null; // Or a loading component
    return (
        // Your previous render code here
    );
}