![](/img/trans.png)
[英]Getting error when trying to pull data from firebase collection REACT: TypeError: Cannot read properties of undefined (reading 'map')
[英]Error when trying to .map over props in React-Redux when getting data from Firebase
我一直在努力解决这个问题,但我不知道自己做错了什么。 我已经设置了 React-Redux 以从 Firebase 导入/编辑数据。 我可以获取数据,但似乎无法映射数据库以使用每个数据库项目。 每个项目都将是一个对象,其中包含有关北方乡村小径问题的各种数据。 它将具有名称、位置、描述等...
我可以从 Firebase 访问数据。 我可以console.log
数组,其中包含每个跟踪对象的信息。 我无法让它显示在屏幕上。
我要么得到这个error: TypeError: Cannot read property 'map' of undefined
要么关于 Objects are not valid as a React child 的错误。
下面是我的一些相关代码:
动作.js
export const fetchTrailItems = () => async dispatch => {
trailItemsRef.on("value", snapshot => {
dispatch({
type: FETCH_TRAILITEMS,
payload: snapshot
});
});
};
reducer.js
const snapshotToArray = snapshot => {
let returnArr = [];
snapshot.forEach(function(childSnapshot) {
let item = childSnapshot.val();
item.key = childSnapshot.key;
returnArr.push(item);
});
return returnArr;
};
const getTrailData = (state = [], action) => {
switch (action.type) {
case FETCH_TRAILITEMS:
const newData = snapshotToArray(action.payload);
console.log(newData);
return { ...state, trailItems: newData };
default:
return state;
}
};
const rootReducer = combineReducers({
form: formReducer,
auth: authReducer,
trailwork: trailworkReducer,
trailData: getTrailData
});
export default rootReducer;
TrailWorkList.js
import React from "react";
import TrailworkItem from "./TrailworkItem";
import { connect } from "react-redux";
import * as actions from "../actions";
class TrailworkList extends React.Component {
componentDidMount() {
this.props.fetchTrailItems();
}
renderTrailList = () => {
console.log(this.props.trailData.trailItems);
return this.props.trailData.trailItems.map(trailItem => {
return (
<p>{trailItem}</p>
// <TrailworkItem trailItem={trailItem} key={this.props.trailItem.key} />
);
});
};
render() {
return (
<div className="ui relaxed divided list">
Hi Im a list
{this.renderTrailList()}
</div>
);
}
}
const mapStateToProps = state => {
return {
trailData: state.trailData
};
};
export default connect(mapStateToProps, actions)(TrailworkList);
我可以console.log(this.props.trailData.trailItems)
并得到这个:在此处输入图像描述
但是,如果我尝试对它进行映射,我只会得到一个错误和“未定义”,除了“未定义”之外, console.log
中什么也没有出现。 我想我包含了所有必要的代码。 如果有人可以提供任何帮助,我将不胜感激。
需要先检查你是否有this.props.trailData
。
renderTrailList = () => {
console.log(this.props.trailData.trailItems);
if (this.props.trailData) {
return this.props.trailData.trailItems.map(trailItem => {
return ( <
p > {
trailItem
} < /p>
// <TrailworkItem trailItem={trailItem} key={this.props.trailItem.key} />
);
});
} else {
return <p > Loading < /p>
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.