首页 > 解决方案 > 如何把它变成一个函数

问题描述

我有这个 redux 钩子。我基本上fetchStudents将为学生、学区、学校等创建。我不想重写此代码,而是希望能够传入 URL 和类型。我怎样才能做到这一点?

import fetch from 'isomorphic-fetch';
import { createAction } from 'utils/actionUtils';
import * as types from './StudentConstants';

export const setLoading = createAction(types.SET_LOADING);

const getStudents = students => ({
  type: types.SET_STUDENTS,
  payload: students,
});

export const fetchStudents = (students) => {
  return (dispatch) => {
    return fetch('http://gsndev.com/gsndb/student/', {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        Authorization: `JWT ${localStorage.token}`,
      },
    })
      .then(response => response.json())
      .then((s) => {
        dispatch(getStudents(s));
      })
      .catch(error => (error));
  };
};

标签: reactjsredux

解决方案


fetchStudents是正常功能。因此,传递您想要的任何参数并将这些参数用于分支逻辑。

例如

export const fetchStudents = (type, url) => {
    return (dispatch) => {
        return fetch(url, {   // Here you may put url
            method: 'GET',
            headers: {
                Accept: 'application/json',
                Authorization: `JWT ${localStorage.token}`,
            },
        })
        .then(response => response.json())
        .then((s) => {
            switch (type) {
                case 'students':
                    dispatch(getStudents(s));
                    break;
                case 'district':
                    dispatch(getDistricts(s));  // There can be action creator for districts
                    break;
                // And so on for other types
            }
        })
        .catch(error => (error));
    };
};

推荐阅读