簡體   English   中英

對象作為嘗試返回 swal 的 React 子項(找到:[object Promise])無效

[英]Objects are not valid as a React child (found: [object Promise]) trying to return swal

我正在嘗試在 state 未定義時進行條件渲染,並且我想向用戶展示他尚未選擇客戶端的甜蜜提醒。 但我收到此錯誤:

對象作為 React 子級無效(找到:[object Promise])。 如果您打算渲染一組子項,請改用數組。

片段:

const location = useLocation();

const ClientNotSelected = () => {
    return (
        <div>
            {
                Swal.fire({
                    title: 'Are you sure?',
                    text: "You won't be able to revert this!",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Yes, delete it!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        Swal.fire(
                            'Deleted!',
                            'Your file has been deleted.',
                            'success'
                        )
                    }
                })

            }

        </div>

    )
}


if (location.state === undefined) {
    return <ClientNotSelected />;
} 

無需創建和渲染組件來觸發警報。

您可以將Swal.fire()移動到您的 if 語句中。

像這樣:

if (location.state === undefined) {
  Swal.fire({
    title: "Are you sure?",
    text: "You won't be able to revert this!",
    icon: "warning",
    showCancelButton: true,
    confirmButtonColor: "#3085d6",
    cancelButtonColor: "#d33",
    confirmButtonText: "Yes, delete it!",
  }).then((result) => {
    if (result.isConfirmed) {
      Swal.fire("Deleted!", "Your file has been deleted.", "success");
    }
  });
}

我是如何解決的:

我創造了

const [clientSelected, setClientSelected] = useState(false);

我在useEffect中檢查了它,里面有swal.fire它沒有給出任何問題/錯誤

useEffect(()=>{
    if (location.state === undefined){
        setClientSelected(false);
        Swal.fire({
            title: 'Are you sure?',
            text: "You won't be able to revert this!",
            icon: 'warning',
            confirmButtonColor: '#3085d6',
            confirmButtonText: 'Ok'
        }).then((result) => {
            if (result.isConfirmed) {
                history.goBack();
            }
        })
    }
    else{
        setClientSelected(true);
    }
})

下面我繼續使用相同的條件,但檢查新的 var clientSelected

if (!clientSelected) {
    return <h1>Select a client</h1>;
} else {
    return <Component />;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM