reactjs - 如何把它变成一个函数
问题描述
我有这个 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));
};
};
解决方案
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));
};
};
推荐阅读
- mysql - SQL 语法错误,请查看手册
- cryptography - 在 micro-ecc 中的 uECC_make_key 方法中使用自定义的随机数生成密钥对 - Riot OS
- linux - Linux,存储文件的 CPU 架构
- hql - 查询转换 Sql 到 HQL - Joins and From (SELECT ...)
- android - 如何区分方向变化和暂停应用程序?
- opencv - 我的 Google Colab PRO 在训练期间断开连接 - 如何保存和恢复我的训练
- r - 如何使用 R 中的 acf 和 pacf 图确定 AR/MA 项的顺序
- python - 如何从 Python 中网页内的链接获取数据?
- deep-learning - Pytorch 中的正确验证损失?
- java - 我无法获得 JSON 数据“预期为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ 处为 BEGIN_OBJECT”