尝试在 <Create/> 上使用 react-admin 转换功能 [英] Trying to use react-admin transform function on <Create />

查看:63
本文介绍了尝试在 <Create/> 上使用 react-admin 转换功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 react-admin 的新手,我正在尝试构建自定义图片库输入.它应该显示一个带有图像的模式(数据已经被提取并存储在 redux 中),以便用户可以选择一个或多个图像(选择后,一个动作被调度来更新减速器的值),我需要这些选择的图像 ID 在转换中<Create/> 上的函数,以便我可以在调用 dataProvider 方法之前添加所需的数据.

I'm new to react-admin and I am trying to build a custom image gallery input. it should show a modal with images (data is already fetched and stored in the redux) so the user can select one or more images (upon selection an action is dispatched to update the reducer's value) and I need these selected images ids in the transform function on <Create /> so I can add the required data before dataProvider method is called.

但我有一个奇怪的问题,这可能是因为我缺乏反应知识.在下面的代码片段中,我尝试获取 useReducer 的值,然后将其添加到表单中.

but I have a weird issue, that might be because of my lack of react knowledge. in the snippet below, I try to get the useReducers value and then add it to the form.

import React, { useReducer, useMemo, useEffect, useCallback } from 'react';
import { Create as Ra_create } from 'react-admin';

const ctxInitialValues = {};

const galleryCtx = React.createContext(ctxInitialValues);

const CreateWithGallery = (props) => {
    const [selectedImages, dispatch] = useReducer((state, { type, payload }) => {
        switch (type) {
            case 'UPDATE_STATE':
                return { ...payload };
            case 'INIT_RECORD':
                return {
                    ...state,
                    [payload]: [],
                };
            default:
                return state;
        }
    }, ctxInitialValues);

    const updateSelection = (record, image, operation) => {
        if (operation === 'add') {
            let newState = {
                ...selectedImages,
                [record]: [...selectedImages[record], image],
            };
            dispatch({
                type: 'UPDATE_STATE',
                payload: newState,
            });
        } else if (operation === 'remove') {
            let newState = {
                ...selectedImages,
                [record]: selectedImages[record].filter((item) => item.id !== image.id),
            };
            dispatch({
                type: 'UPDATE_STATE',
                payload: newState,
            });
        }
    };

    const transformPayload = (data) => {
        let transformed = {
            ...data,
        };
        // but I get {} here
        for (let record in selectedImages) {
            transformed[record] = selectedImages[record].map((item) => ({
                id: item.id,
            }));
        }
        return transformed;
    };

    useEffect(() => {
        console.log(selectedImages);
        // I get fresh values here
    }, [selectedImages]);

    const initializeRecord = (record) => {
        dispatch({
            type: 'INIT_RECORD',
            payload: record,
        });
    };

    return (
        <galleryCtx.Provider
            value={{
                selectedImages,
                updateSelection,
                initializeRecord,
            }}
        >
            <Ra_create {...props} transform={transformPayload}>
                {props.children}
            </Ra_create>
        </galleryCtx.Provider>
    );
};

export { galleryCtx };
export default CreateWithGallery;

当我尝试访问转换函数中的 selectedImages 值时,我得到 {},这是初始状态.我曾尝试使用 useCallback 和 useMemo 来确保每次调度后更改值,但没有任何区别.这个问题中也有类似的行为:React Admin:如何传递状态以进行转换

when I try to access the selectedImages values in the transform function I get {}, which is the initial state. I have tried using useCallback and useMemo to make sure the values are changed after each dispatch but it did not make any difference. there's also a similar behavior in this question as well: React Admin: how to pass state to transform

如何在转换函数中使用状态?

how can I use state in the transform function?

推荐答案

我最终在组件上设置了变换道具(在自定义工具栏中):

I ended up with setting the transform prop on the component (in custom toolbar):

 const CustomToolbar = (props: any) => {

        const transform = useCallback((data: any) => {
            return {
                ...data,
                files: something_from_state,
            };
        }, [something_from_state]);


        const handleClick = () => {
        };


        return <Toolbar {...props}>
            <SaveButton
                handleSubmitWithRedirect={handleClick} transform={transform}/>
        </Toolbar>
    };

这篇关于尝试在 &lt;Create/&gt; 上使用 react-admin 转换功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆