【发布时间】:2019-06-16 12:22:08
【问题描述】:
我正在尝试创建一个名为“提案”的 React 组件,它将呈现从 Django 后端接收到的信息的表格列表。
我正在使用 Reactable-Search component 来形成表格,但是当我尝试将 this.props.proposals 值(例如 id 和 proj_name)映射到表格单元格时,我一直收到错误 - 未捕获TypeError:无法读取未定义的属性“单元格”
真的不知道为什么,因为当我将 this.props.proposals 直接映射到典型 html 表格标签的渲染返回中时,它正在工作,即渲染后端数据正常。我还在其他情况下使用了带有映射的 Reactable-Search 组件,它运行良好。
this.props.proposals 的日志输出还显示了正确的对象数组...:
如果有人能把我推向正确的方向,我真的很感激,谢谢!
提案组件:
import React, { Component } from "react";
import { connect } from "react-redux";
import SearchTable from "reactable-search";
import { proposals } from "../actions";
class Proposals extends Component {
componentDidMount() {
this.props.fetchProposals();
}
constructor(props) {
super(props);
this.state = {};
}
render() {
var rows = this.props.proposals.map(p => ({
selected: this.state.selectedRow === p.id,
onClick: () => {
this.setState({ selectedRow: p.id });
},
cells: {
"#": p.id,
"Project Name": p.proj_name
}
}));
return (
<SearchTable
showExportCSVBtn={true}
searchPrompt="Type to search"
rows={rows}
/>
);
}
}
const mapStateToProps = state => {
return {
proposals: state.proposals
};
};
const mapDispatchToProps = dispatch => {
return {
fetchProposals: () => {
dispatch(proposals.fetchProposals());
}
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Proposals);
提案reducer:
const initialState = [];
export default function proposals(state = initialState, action) {
switch (action.type) {
case "FETCH_PROPOSALS":
return [...action.proposals];
default:
return state;
}
}
提案操作
export const fetchProposals = () => {
return dispatch => {
let headers = { "Content-Type": "application/json" };
return fetch("/api/proposals/", { headers })
.then(res => res.json())
.then(proposals => {
return dispatch({
type: "FETCH_PROPOSALS",
proposals
});
});
};
};
【问题讨论】:
-
你能把你的
proposals减速机的initialState贴出来吗?尝试在render方法中记录this.props.proposals,看看它是否真的打印了预期的输出。 -
嗨 Eugene - 当我记录 this.props.proposals 时,它确实输出了预期的对象数组......我还添加了减速器和动作文件。谢谢
标签: javascript django reactjs mapping react-props