如何在Admin On Rest中更新后展示服务器返回的自定义消息?
在Admin-on-Rest中展示服务器返回的自定义更新消息
其实这个需求很好实现,咱们可以借助Admin-on-Rest自带的showNotification工具和Material-UI的Snackbar组件,结合你现有的ApproveButton代码来修改就行。我给你一步步拆解:
核心思路
Admin-on-Rest提供了withNotify高阶组件,能把触发Snackbar的showNotification方法注入到组件props里。我们只需要在更新请求成功后,从服务器返回的响应里提取自定义消息,再调用这个方法就行。
修改后的代码示例
基于你提供的ApproveButton.js,调整后的代码大概是这样:
import React, { Component } from 'react'; import { withMutation, showNotification, withNotify } from 'admin-on-rest'; import Button from '@material-ui/core/Button'; class ApproveButton extends Component { handleClick = async () => { const { mutate, record, showNotification } = this.props; try { // 发送更新请求,拿到服务器返回的响应 const response = await mutate(`/reviews/${record.id}/approve`, { method: 'PUT', }); // 从响应里提取自定义消息,没有的话用默认值兜底 const customMessage = response.message || '审核已成功通过!'; // 触发Snackbar展示消息,第二个参数是消息类型(success/warning/error/info) showNotification(customMessage, 'success'); } catch (error) { // 错误情况同理,提取自定义错误消息 const errorMessage = error.message || '审核操作失败,请稍后重试'; showNotification(errorMessage, 'warning'); } }; render() { return <Button onClick={this.handleClick}>通过审核</Button>; } } // 用withNotify包裹组件,注入showNotification方法 export default withNotify(withMutation(ApproveButton));
关键细节说明
- 获取服务器消息:这里假设你的后端返回的响应里有
message字段存储自定义内容,如果你的API结构不同(比如消息在response.data.msg里),直接调整提取逻辑就行。 - 消息类型与样式:
showNotification的第二个参数决定了Snackbar的样式,success是绿色,warning是黄色,error是红色,按需选择。 - 自定义Snackbar行为:如果需要调整消息显示时长、位置等,可以加第三个参数,比如:
这样消息会显示5秒后自动消失(默认是4秒)。showNotification(customMessage, 'success', { autoHideDuration: 5000 });
内容的提问来源于stack exchange,提问作者Ali Hesari
相关产品推荐
相关产品推荐

