當前正在進行reactx項目。Redux操作調用返回undefined,然後定義
我能夠調用我的動作fetchProjects()來處理axios獲取請求到服務器。
與我的代碼問題是,它將控制檯日誌記錄爲未定義,然後使用我的項目列表填充我的狀態。
我的目標是在調用渲染函數時在屏幕上呈現項目列表。但是當我調用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)
這裏是執行GET請求
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'));
});
}
}
這裏的動作是減速
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;
}
你可以添加你的減速器代碼嗎? – WorldSEnder
是的,那個減速器在 – WilomGfx
@WorldSEnder更新 –