如何使用Inertia React和Laravel返回简单的Flash消息?



当用户完成表单并重定向回"仪表板"时,我正试图在我的应用程序中为用户返回Flash消息。

我是Inertia的新手,所以可能是我,但文档似乎不太深入,我想知道如何正确地调用这个Flash函数,并在Dashboard.js文件的前端获取它。

这是我的控制器和仪表板文件代码:

public function completeForm(Request $request){
$request->validate([
'commitment' => 'required|string',
'partner' => 'required|string',
'question' => 'required|string',
]);
$user = Auth::user();

$user->update([
'partner' => $request->partner,
'commitment' => $request->commitment,
'question' => $request->question,
]);
return redirect('/dashboard')->with('success', 'Your profile has been updated!');
}

和仪表板:

export default function Dashboard(props) {
const [modalVisible, setModalVisible] = useState(false);
console.log(props);
const handleModal = () => {
setModalVisible(true);
};
return (
<Empty
auth={props.auth}
errors={props.errors}
header={
<h2 className="font-semibold text-xl text-gray-800 leading-tight">
Dashboard
</h2>
}
>
<Head title="Dashboard" />
<div className="py-12">
<div className="max-w-3xl mx-auto sm:px-6 lg:px-8">
{/* <div className="bg-white overflow-hidden shadow-sm sm:rounded-lg">
<div className="p-6 bg-white border-b border-gray-200">
You're logged in!
</div>
</div> */}
<div className="bg-yellow-500 px-1 py-1 inline-block ">
<p className="text-6xl font-bold uppercase text-white custom">
Your Details
</p>
</div>

{/* {flash.message && <div class="alert">{flash.message}</div>} */}
<div className="mt-16 border-2 border-yellow-500 p-2">
<p className="text-xl font-bold italic">
Next, we'd need you to submit your questions to us
for review
</p>
<div className="flex flex-col">
<p className="italic text-gray-400 text-lg font-medium mt-2">
Please use the button below to start filling out
your form:
</p>
<a
href="/commitment-questions"
className="text-center bg-yellow-500 py-2 px-3 self-center mt-8 text-2xl custom text-white font-bold mb-4"
>
Complete Form
</a>
</div>
</div>

</div>
</div>
</Empty>
);
}

我知道这可能很简单,提前感谢您在这方面的帮助!

共享一条全局可用的flash消息,然后在React组件中需要的地方使用它:https://inertiajs.com/shared-data#flash-消息

class HandleInertiaRequests extends Middleware
{
public function share(Request $request)
{
return array_merge(parent::share($request), [
'flash' => [
// in your case, you named your flash message "success"
'message' => fn () => $request->session()->get('message')
],
]);
}
}

然后在任何React组件中使用:

import { usePage } from '@inertiajs/inertia-react'
export default function Dashboard() {
const { flash } = usePage().props
return (
<main>
<div>
{flash.message && (
<div class="alert">{flash.message}</div>
)}
</div>
</main>
)
}

相关内容

  • 没有找到相关文章

最新更新