我如何在 react-redux 中正确地执行 GET 请求?

How do i properly do a GET request in react-redux?

我的目标是基本上在 react-redux 中做一个基本的 GET 请求。我知道如何使用 POST 执行此操作,但不知道如何使用 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;
  }


}
  1. 如果您没有注意到,您的 allCourses() 中有两个 return。
  2. 我的代码库中有类似的代码,但我没有在 fetch 和 response.json() 前面使用 return,因为该函数应该 return 操作对象。

首先,onGetCourses: () => dispatch(getCourses) 应更改为 onGetCourses: () => dispatch(getCourses())(您需要实际调用动作创建器)。

当涉及到应该在哪里调用操作时,在 componentDidMount 中完成绝对没问题,正如您所做的那样。