You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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));

关键细节说明

  1. 获取服务器消息:这里假设你的后端返回的响应里有message字段存储自定义内容,如果你的API结构不同(比如消息在response.data.msg里),直接调整提取逻辑就行。
  2. 消息类型与样式:showNotification的第二个参数决定了Snackbar的样式,success是绿色,warning是黄色,error是红色,按需选择。
  3. 自定义Snackbar行为:如果需要调整消息显示时长、位置等,可以加第三个参数,比如:
    showNotification(customMessage, 'success', { autoHideDuration: 5000 });
    
    这样消息会显示5秒后自动消失(默认是4秒)。

内容的提问来源于stack exchange,提问作者Ali Hesari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:04:45