[英]How do i properly do a GET request in react-redux?
My goal is to basically do a basic GET request in react-redux. 我的目标是基本上在react-redux中执行一个基本的GET请求。 I know how to do it with POST but not with GET because there is no event that is triggering the action.
我知道如何使用POST而不是GET,因为没有事件触发操作。
Heres' the code for action 这是行动代码
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
});
})
}
});
}
}
Where do i trigger this to get the data? 我在哪里触发此操作以获取数据? in component?
在组件中?
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);
I tried this but it doesn't work. 我试过了,但是没有用。
Course Reducer 减径器
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;
}
}
First, onGetCourses: () => dispatch(getCourses)
should be changed to onGetCourses: () => dispatch(getCourses())
(you need to actually invoke the action creator). 首先,
onGetCourses: () => dispatch(getCourses)
更改为onGetCourses: () => dispatch(getCourses())
(您需要实际调用动作创建者)。
When it comes to where you should call the action, it is absolutely fine to do it in componentDidMount
, as you have done. 对于应该调用该操作的位置,完全可以在
componentDidMount
,就像您所做的一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.