我正在使用React来调用后端API并检索JSON对象数组。我能够将对象数组和单个对象打印到控制台,但是当我尝试访问对象内部的值时,我会遇到类型错误。我正在使用助焊剂框架。这是我的动作:
//ratingsActions.js
import dispatcher from "../appDispatcher";
import * as ratingsApi from "../api/ratingsApi";
import actionTypes from "./actionTypes";
export function loadRatings() {
return ratingsApi.getRatings().then(ratings => {
dispatcher.dispatch({
actionType: actionTypes.LOAD_RATINGS,
ratings: ratings
});
});
}
还有我的商店:
//ratingsStore.js
import { EventEmitter } from "events";
import Dispatcher from "../appDispatcher";
import actionTypes from "../actions/actionTypes";
const CHANGE_EVENT = "change";
let _ratings = [];
class RatingsStore extends EventEmitter {
addChangeListener(callback) {
this.on(CHANGE_EVENT, callback);
}
removeChangeListener(callback) {
this.removeListener(CHANGE_EVENT, callback);
}
emitChange() {
this.emit(CHANGE_EVENT);
}
getRatings() {
return _ratings;
}
}
const store = new RatingsStore();
Dispatcher.register(action => {
switch (action.actionType) {
case actionTypes.UPDATE_RATINGS:
store.emitChange();
break;
case actionTypes.LOAD_RATINGS:
_ratings = action.ratings;
store.emitChange();
break;
default:
}
});
export default store;
//component
const [ratings, setRatings] = useState(ratingsStore.getRatings());
useEffect(() => {
ratingsStore.addChangeListener(onChange);
if (ratingsStore.getRatings().length === 0) loadRatings();
return () => ratingsStore.removeChangeListener(onChange);
}, []);
function onChange() {
setRatings(ratingsStore.getRatings());
}
console.log(ratingsStore.getRatings()[0]) ;
现在,在我的组件中,我尝试执行console.log(ratingsStore.getRatings()[0];)
,该操作返回如下图所示的对象:
但是,如果我尝试执行console.log(ratingsStore.getRatings()[0].rating;)
,则会收到与主题中相同的错误。这是怎么了?
更新:好的,我现在更加困惑。当我将window.ratings=ratings
导出到浏览器时,我能够访问数组中对象的每个字段,例如ratings[0].teamName
,并将其打印到控制台。但是ratings[0].teamName
仍无法在应用程序中工作...