我的目標是基本上在react-redux中做一個基本的GET請求。我知道如何使用POST來做到這一點,但不使用GET,因爲沒有事件觸發該動作。如何在react-redux中正確執行GET請求?
繼承人的行動
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
});
})
}
});
}
}
我在哪裏可以觸發此獲取數據的代碼?在組件中?
import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import { getCourses } from '../actions/course';
class Course extends React.Component {
componentDidMount() {
this.props.onGetCourses();
}
allCourses() {
console.log(this.props.onGetCourses());
return this.props.courses.map((course) => {
return(
<li>{ course.name }</li>
);
});
return this.props
}
render() {
return (
<div>
<ul>
{ this.allCourses() }
</ul>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
courses: state.course.courses
}
}
const mapDispatchToProps = (dispatch) => {
return {
onGetCourses:() => dispatch(getCourses)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Course);
我試過這個,但它不起作用。
課程減速
const initialState = {
courses: []
};
export default function course(state= initialState, action) {
switch (action.type) {
case 'GET_COURSES':
return Object.assign({}, state, {
courses: action.courses
})
default:
return state;
}
}
傻我,謝謝,現在它顯示所有的數據! – sinusGob