`Mui DataGrid` 中的 `renderCell` 不会根据条件渲染。

huangapple go评论102阅读模式
英文:

renderCell from Mui DataGrid not rendering conditionally

问题

我有一个用于我的 Mui DataGrid 的简单设置。不过,我遇到的问题是 renderCell 不会在条件下渲染我的元素。

`Mui DataGrid` 中的 `renderCell` 不会根据条件渲染。

它应该默认显示一个 EditIcon 按钮(铅笔),一旦我点击它,它应该调用 fetchSomething - 它确实这样做 - 并通过将 isLoading 设置为 true 切换到 Mui CircularProgress 元素,但是 CircularProgress 元素从未显示出来。

我通过快速使用 useEffect 进行了测试,以查看状态是否发生了变化,它确实从 false 变为 true,然后再次变为 false,但是 CircularProgress 永远不可见。

我是否遇到了 ID 方面的问题?有解决此问题的方法吗?

const Component = () => {
    const [isLoading, setIsLoading] = useState(false);

    const fetchSomething = (event) => {

        setIsLoading(true);

        fetch(event.id)
         .then(() => doSmth())
         .catch((error) => console.log(error))
         .finally(() => setIsLoading(false));
    };


    const usersTableColumns = [
        {
            field: 'id',
            headerName: 'ID',
            width: 200,
            flex: 1,
        },
        {
            field: 'username',
            headerName: '用户名',
            width: 170,
            flex: 1,
        },
        {
            field: 'action',
            headerName: '编辑',
            sortable: false,
            renderCell: (params) => (isLoading ? <CircularProgress size={30} /> : (
                <EditIcon onClick={fetchSomething} />
            )),
        },
    ];

    return(
        <DataGrid rows={rows} columns={usersTableColumns}/>
    );
}

**编辑**
根据上述逻辑只要我点击其中一个铅笔所有铅笔都应该变成旋转器因此我尝试动态添加 `ids` 到状态并在显示 `CircularProgress` 时检查某个 `id`但似乎状态更新对于 `renderCell` 不会显示出来

[1]: https://i.stack.imgur.com/MEBZx.png
英文:

I have a simple setup for my Mui DataGrid. The issue I have though, is that renderCell isn't rendering my elements conditionally.

`Mui DataGrid` 中的 `renderCell` 不会根据条件渲染。

It should show per default an EditIcon button (the pencil) and as soon as I click on it, it should call fetchSomething - which it does - and switch to the Mui CircularProgress element by setting isLoading to true but the CircularProgress element is never displayed.

I tested quickly via a useEffect to see if the state changes and it does change from false to true then again to false but the CircularProgress is nowhere to be seen.

Am I having issues with ids? Any way to solve this?

const Component = () =&gt; {
    const [isLoading, setIsLoading] = useState(false);

    const fetchSomething = (event) =&gt; {

        setIsLoading(true);

        fetch(event.id)
         .then(() =&gt; doSmth())
         .catch((error) =&gt; console.log(error))
         .finally(() =&gt; setIsLoading(false));
    };


    const usersTableColumns = [
		    {
			    field: &#39;id&#39;,
			    headerName: &#39;ID&#39;,
			    width: 200,
			    flex: 1,
		    },
		    {
			    field: &#39;username&#39;,
			    headerName: &#39;USER NAME&#39;,
			    width: 170,
			    flex: 1,
		    },
		    {
			    field: &#39;action&#39;,
			    headerName: &#39;Edit&#39;,
			    sortable: false,
			    renderCell: (params) =&gt; (isLoading ? &lt;CircularProgress size={30} /&gt; : (
				    &lt;EditIcon onClick={fetchSomething} /&gt;
			    )),
            },
    ];

    return(
        &lt;DataGrid rows={rows} columns={usersTableColumns}/&gt;
    );
}

EDIT
According to the logic above all pencils should become spinners as soon as I click on one of them, so I tried adding dynamically the ids to the state and checking for a certain id when displaying CircularProgress but it seems like the state updates just don't show up for renderCell.

答案1

得分: 0

以下是已经翻译好的部分:

For anyone struggling with this the solution is very simple. It took me a bit but I got it.

对于任何遇到这个问题的人,解决方法非常简单。花了一点时间,但我弄明白了。

You need to export the content of renderCell into a new component and import it. You will also have to put the hook into that component. This will create a component for each row so you will not have any issues with ids.

你需要将 renderCell 的内容导出到一个新组件并导入它。你还需要将 hook 放入该组件中。这将为每一行创建一个组件,这样你就不会遇到 ids 的问题。

Even then, conditionally rendering the cell would not work anyways.

即使如此,有条件地渲染单元格也不会起作用。

https://mui.com/x/react-data-grid/column-definition/

https://mui.com/x/react-data-grid/column-definition/

const Component = ({
    fetchSmth, params,
}) => {
    const [isLoading, setIsLoading] = useState(false);

    const doSmth = async () => {
        setIsLoading(true);
        await fetchSmth(params.row);
        setIsLoading(false);
    };

    return (
        <Tooltip title='Some title'>
            <IconButton
                variant='contained'
                onClick={(e) => {
                    doSmth(e);
                }}
            >
                {isLoading ? <CircularProgress size={30} /> : <EditIcon />}
            </IconButton>
        </Tooltip>
    );
};

export default Component;

renderCell 只需渲染这个组件。你可以测试它(如果你的 REST 调用速度太快,可以通过在移动模式下限制浏览器速度来测试)。
renderCell 只需渲染这个组件。你可以测试它(如果你的 REST 调用速度太快,可以通过在移动模式下限制浏览器速度来测试)。

英文:

For anyone struggling with this the solution is very simple. It took me a bit but I got it.

You need to export the content of renderCell into a new component and import it. You will also have to put the hook into that component. This will create a component for each row so you will not have any issues with ids.

Even then, conditionally rendering the cell would not work anyways.

`Mui DataGrid` 中的 `renderCell` 不会根据条件渲染。

https://mui.com/x/react-data-grid/column-definition/

const Component = ({
	fetchSmth, params,
}) =&gt; {
	const [isLoading, setIsLoading] = useState(false);

	const doSmth= async () =&gt; {
		setIsLoading(true);
		await fetchSmth(params.row);
		setIsLoading(false);
	};

	return (
		&lt;Tooltip title=&#39;Some title&#39;&gt;
			&lt;IconButton
				variant=&#39;contained&#39;
				onClick={(e) =&gt; {
					doSmth(e);
				}}
			&gt;
				{isLoading ? &lt;CircularProgress size={30} /&gt; : &lt;EditIcon /&gt;}
			&lt;/IconButton&gt;
		&lt;/Tooltip&gt;
	);
};

export default Component;

renderCell has just to render this component. You can test this (if your REST call is too fast by throttling your browser in mobile mode.

huangapple
  • 本文由 发表于 2023年3月8日 19:12:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75672264.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定