Im新的React和Redux,仍然有點混淆。TypeError:無法讀取react-redux中未定義的屬性'map'
我的目標是使用GET請求在HTML中呈現一堆json數據。我正在使用react和redux來管理對象的狀態,但我相信我的問題是數據甚至不存在
所以基本上每當有人請求URL /課程時,他/她都會看到一堆數據在json中。
我得到錯誤的組件
TypeError: Cannot read property 'map' of undefined
下面的代碼
行動
export function getCourses() {
return (dispatch) => {
return fetch('/courses', {
method: 'get',
headers: { 'Content-Type', 'application/json' },
}).then((response) => {
if (response.ok) {
return response.json().then((json) => {
dispatch({
type: 'GET_COURSES',
courses: json.courses
});
})
}
});
}
}
減速
export default function course(state={}, action) {
switch (action.type) {
case 'GET_COURSES':
return Object.assign({}, state, {
courses: action.courses
})
default:
return state;
}
}
組件
import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
class Course extends React.Component {
allCourses() {
return this.props.courses.map((course) => {
return(
<li>{ course.name }</li>
);
});
}
render() {
return (
<div>
<ul>
{ this.allCourses() }
</ul>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
courses: state.courses
}
}
export default connect(mapStateToProps)(Course);
指數減速,在這裏我結合一切
import { combineReducers } from 'redux';
import course from './course';
export default combineReducers({
course,
});
配置商店,在那裏我存儲INTIAL狀態和減速
import { applyMiddleware, compose, createStore } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';
export default function configureStore(initialState) {
const store = createStore(
rootReducer,
initialState,
compose(
applyMiddleware(thunk),
typeof window == 'object' && typeof window.devToolsExtension !== 'undefined' ? window.devToolsExtension() : f => f
)
);
return store;
}
我相信爲什麼數據不存在,因爲我沒有打電話給行動?任何幫助,將不勝感激。
那是你唯一的減速?還是你在其他地方把減速器結合起來?你能告訴我們你在哪裏初始化商店? –