【发布时间】:2019-07-08 16:47:36
【问题描述】:
当我使用 react-admin 组件 <List> <Edit> 时,我的 authProvider 中会调用 AUTH_ERROR。
但是当我在自定义组件中使用 dataProvider 时,AUTH_ERROR 不会被调用。
如文档中所述,如果任何 API 调用返回任何错误,authProvider 将使用类型 AUTH_ERROR 捕获它。
我正在使用教程中的默认数据提供程序:
const API_URL = process.env.REACT_APP_API_URL;
const convertDataProviderRequestToHTTP = (type, resource, params) => {
let url = '';
const token = localStorage.getItem('token');
const options = {
headers: new Headers({
'Accept': 'application/ld+json',
'Content-Type': 'application/ld+json',
'Authorization': `Bearer ${token}`,
}),
};
switch (type) {
case 'GET_GENERAL': {
url = `${API_URL}/${resource}?${stringify(params)}`;
break;
}
case GET_ONE:
url = `${API_URL}/${resource}/${params.id}`;
break;
case UPDATE:
url = `${API_URL}/${resource}/${params.id}`;
options.method = 'PUT';
options.body = JSON.stringify(params.data);
break;
case DELETE:
url = `${API_URL}/${resource}/${params.id}`;
options.method = 'DELETE';
break;
default:
throw new Error(`Unsupported fetch action type ${type}`);
}
return {url, options};
};
const convertHTTPResponseToDataProvider = (response, type, resource, params) => {
const {json} = response;
switch (type) {
case GET_LIST:
case GET_MANY_REFERENCE:
let data = json['hydra:member'];
return {
data: data,
total: json['hydra:totalItems'],
};
case CREATE:
return {data: json};
default:
return {data: json};
}
};
export default (type, resource, params) => {
const {fetchJson} = fetchUtils;
const {url, options} = convertDataProviderRequestToHTTP(type, resource, params);
return fetchJson(url, options)
.then (response => {console.log(response) ; return response})
.then(response => convertHTTPResponseToDataProvider(response, type, resource, params));
};
在我的自定义组件中,我是这样称呼 dataProvider 的:
class MyClass extends PureComponent {
constructor(props) {
super(props);
this.state = {
data: null,
};
}
componentDidMount() {
dataProvider('GET_GENERAL', 'myRessource', {
"perPage": 1,
"page": 1,
"oneField.id": 123,
"twoField.id": 132,
"threeField.id": 145,
})
.then(response => response.data)
.then((response) => {
this.setState({data: response});
})
};
render() {
const {data} = this.state;
return <div>{data.field}</div>
}
}
const enhance = compose(
withStyles(styles),
connect(mapStateToProps, {customAction}),
translate
);
export default enhance(MyClass);
当然我的 authProvider 是这样配置的:
// ...
if (type === AUTH_ERROR) {
const {status} = params;
if (status === 401 || status === 403) {
console.log('here');
return Promise.reject();
}
console.log('there');
return Promise.resolve();
}
// ...
在我的示例中,我的 API 返回 HTTP 401,并且在控制台中我永远不会得到“这里”或“那里”,因此我无法对 AUTH_ERROR 执行自定义操作。
任何想法我做错了什么?
【问题讨论】:
标签: react-admin