在组件中,我显示项目列表(通过map
函数)。但是,在map
之外,我需要显示其他信息。但是,只有在map
内进行迭代时,相关变量才可用。
该变量在Redux商店中看起来像这样:
{1: { id:1, title: 'title', description: 'description' ... }}
下面是组件。地图外的props.assignment[1].title
会引发以下错误:TypeError: Cannot read property 'title' of undefined
。
const SubmissionList = (props) => {
const assignmentId = props.match.params.assignmentId;
useEffect(() => {
if (props.loading != true)
props.fetchSubmissions(assignmentId);
}, [])
if (props.loading) {
return (<div>Loading...</div>)
}
if (props.error) {
return (<div>{props.error}...</div>)
}
return (
<>
<h4>Submissions</h4>
<div className="text-muted">{props.assignment[1].title}</div>
<div className="container">
<div className="row">
{
props.submissionIds.map(submissionId => {
const submission = props.submissions[submissionId];
if (submission != null)
return (
<>
<div className="text-muted">{props.assignment[submission.assignmentId].title}</div>
/>
</>
)
})
}
</div>
</div>
</>
)
}
const mapStateToProps = (state) => ({
submissionIds: state.submissionReducer.submissionIds,
submissions: state.submissionReducer.submissions,
students: state.submissionReducer.students,
assignment: state.submissionReducer.assignment,
loading: state.submissionReducer.loading,
error: state.submissionReducer.error
})
const mapDispatchToProps = (dispatch) => {
return {
fetchSubmissions: (assignmentId) => dispatch(FetchSubmissionsData(assignmentId))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SubmissionList);
这是我读取数据并对其进行规范化的功能:
export function FetchSubmissionsData(assignmentId) {
return dispatch => {
dispatch(dataOperationBegin);
axios.get('api/Submission/GetSubmissionByAssignment', { params: { assignmentId } })
.then(response => {
console.log('Submissions are fetched.');
const submission = new schema.Entity('submissions');
const student = new schema.Entity('student');
const assignment = new schema.Entity('assignment');
submission.define({
student: student,
assignment: assignment
});
const normalizedData = normalize(response.data, [submission]);
dispatch(fetchSubmissionsSuccess(normalizedData))
})
.catch(error => { dataOperationFailure(error) });
}
}
而且,这是减速器的相关部分:
case FETCH_SUBMISSIONS_SUCCESS:
const normalizedData = action.payload.normalizedData;
return {
...state,
loading: false,
error: null,
submissionIds: normalizedData.result,
submissions: normalizedData.entities.submissions,
students: normalizedData.entities.students,
assignment: normalizedData.entities.assignment,
}
我想知道是什么问题。我是否在react-redux中缺少有关事件流的内容?
答案 0 :(得分:0)
我相信您正在对数组props.assignment[1].title
使用语法。实际上,当您需要映射的"1"
键时,您就在这里尝试访问数组的第二个元素。
尝试使用props.assignment["1"].title
或props.assignment.1.title
,看看是否可行。它在map函数中起作用的原因是因为submissionId
是一个字符串而不是数字。