【发布时间】:2018-01-31 07:29:41
【问题描述】:
感谢您过来帮忙。我正在使用 react/redux 应用程序。其中一个组件是使用生命周期方法从 API 检索数据。收到后,数据 JSON 数据将保存在一个数组中。我返回的数据的初始状态是一个空数组。
当监听状态变化的组件被挂载时,数据被渲染到页面上,但是 2 秒后我得到了一个
Uncaught TypeError: jobs.map is not a function
组件使用生命周期方法进行 API 调用并监听状态变化
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getJobs } from '../../actions';
import { Card, Grid, Image, Feed } from 'semantic-ui-react';
// import './home.css';
const renderJobs = jobs => jobs.map((job, i) => (
<Card.Group stackable key={i}>
<Card className="jobscard">
<Card.Content>
<Card.Header href={job.detailUrl} target="_blank">{job.jobTitle}</Card.Header>
<Card.Meta>{job.location}</Card.Meta>
<Card.Description>{job.company}</Card.Description>
</Card.Content>
</Card>
</Card.Group>
));
class GetJobs extends Component {
componentDidMount() {
this.props.getJobs();
}
render() {
const { jobs } = this.props;
return (
<div className="getjobs">
{renderJobs(jobs)}
</div>
);
}
}
export default connect(({ jobs }) => ({ jobs }), { getJobs })(GetJobs);
动作创建者/动作
export const getJobsRequest = () => fetch('https://shielded-brushlands-43810.herokuapp.com/jobs',
)
.then(res => res.json());
// action creator
export const getJobs = () => ({
type: 'GET_JOBS',
payload: getJobsRequest(),
});
减速器
import initialState from './initialState';
export default function (jobs = initialState.jobs, action) {
switch (action.type) {
case 'GET_JOBS_PENDING':
return { ...jobs, isFetching: true };
case 'GET_JOBS_FULFILLED':
return action.payload;
case 'GET_JOBS_REJECTED':
return jobs;
default:
return jobs;
}
}
和初始状态
export default {
userData: {},
jobs: [],
}
对为什么会发生这种情况有任何想法吗?
【问题讨论】:
-
尝试添加默认参数。而不是
const renderJobs = jobs => jobs.map((job, i)...做const renderJobs = (jobs = []) => jobs.map((job, i)...并检查它是否仍然崩溃。
标签: javascript arrays reactjs dictionary redux