【发布时间】:2018-07-16 06:38:06
【问题描述】:
我不明白为什么我的 Redux 道具在 React 组件上显示为空。这是 Redux 状态的截图:
这是可视化的组件。它是父组件的子组件,它获取数据并在元素数组中运行 for 循环。
import React, { Component } from 'react'
import { connect } from "react-redux";
import PropTypes from "prop-types";
class ResourceCard extends Component {
render() {
const { resource } = this.props;
return (
<div className="resource-card">
<div className="resource-card-header">
<span className="res-span-header">{resource.header}</span>
</div>
<div className="resource-card-image">
<img src={resource.image} alt={resource.header} width='300px' />
</div>
<div className="resource-card-desc">
<span className="res-span-desc">{resource.description}</span>
</div>
<div className="resource-card-link">
<span className="res-span">{resource.website}</span>
</div>
</div>
)
}
}
ResourceCard.propTypes = {
resource: PropTypes.object.isRequired,
auth: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
auth: state.auth,
resource: state.resource
});
export default connect(
mapStateToProps,
{}
)(ResourceCard);
虽然 css 正在正确呈现,并且控制台中没有错误,但内容本身并不存在:
这里可能有什么问题?
已编辑:添加操作代码:
// Get Resources
export const getResources = () => dispatch => {
axios
.get("/api/resources")
.then(res =>
dispatch({
type: GET_RESOURCES,
payload: res.data
})
)
.catch(err =>
dispatch({
type: GET_RESOURCES,
payload: null
})
);
};
还有减速器:
import {
ADD_RESOURCE,
GET_RESOURCES,
DELETE_RESOURCE,
GET_RESOURCE
} from "../actions/types";
const initialState = {
resources: [],
resource: {}
};
export default function(state = initialState, action) {
switch (action.type) {
case GET_RESOURCES:
return {
...state,
resources: action.payload
};
case GET_RESOURCE:
return {
...state,
resource: action.payload
};
case DELETE_RESOURCE:
return {
...state,
resources: state.resources.filter(resource => resource._id !== action.payload)
};
case ADD_RESOURCE:
return {
...state,
resources: [action.payload, ...state.resources]
};
default:
return state;
}
}
运行for循环的父组件:
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import ResourceCard from './ResourceCard';
class ResourceFeed extends Component {
render() {
const { resources } = this.props;
return resources.map(resource => <ResourceCard key={resource._id} resource={resource} />)
}
}
ResourceFeed.propTypes = {
resources: PropTypes.array.isRequired
}
export default ResourceFeed;
并且上面的组件包含这个父组件:
<ResourceFeed resources={resources}/>
【问题讨论】:
-
请显示操作代码/reducer 代码
-
编辑中提供。