【问题标题】:Laravel Inertia rendering data from backend to frontendLaravel Inertia 从后端到前端渲染数据
【发布时间】:2023-02-03 05:53:23
【问题描述】:

使用具有 laravel 惯性的 reactJS 是全新的。

我正在尝试将数据从我的数据库呈现到前端。我使用控制器通过使用...从数据库中获取数据

// Show all main categories
public static function index() {
    return MainCategory::all(['main_category_id', 'main_category_name']);
}

然后使用以下代码使用 web.php 将其传递到前端。

Route::get('/', function () {
   return Inertia::render('Admin/Categories', [
        'categories' => MainCategoryController::index()
   ]);
})->name('admin.category-setup');

我目前不知道如何使用reactjs 在前端调用categories。 我怎样才能做到这一点?

【问题讨论】:

  • 看起来你必须在开始工作之前更好地阅读文档。 Laravel 和 Inertia 有一个很好的文档来解释这一切。首先,您应该学习框架和库的基础知识。您的问题表明您不清楚它们是如何工作的......但是考虑到您的代码,您应该让 React 接收 categories 作为道具,请参阅此处的文档:inertiajs.com/pages#creating-pages

标签: php reactjs laravel


【解决方案1】:

我有时通过使用 Inertia 的内置 usePage-Hook for React 来访问传递的道具。当您处理所有前端组件都可以访问的共享数据时,这会派上用场 (https://inertiajs.com/shared-data)。只要您的后端 (Laravel) 代码正常工作并且实际的 categories-Property 被移交给 Categories-Component 或为所有前端共享,您可以这样做:

import React from 'react';    
import { usePage } from '@inertiajs/inertia-react';
    
    function App() {
        const categories = usePage().props.categories;
    
        return (
            <ul>
                {categories.map((category) =>
                    (<li>{category}</li>))}
            </ul>
        );
    }

然而,对我来说最常见的做法是简单地将你在 Laravel 中传递给 Inertia-Component 的相同变量名称传递给 React-Component-Props,就像这样。在我看来,这应该与您的用例完美配合:

import React from 'react';    
    
    function App({categories}) {        
        return (
            <ul>
                {categories.map((category) =>
                    (<li>{category}</li>))}
            </ul>
        );
    }

如果您想了解更多关于 Inertia 的信息,我强烈建议您阅读文档。开发人员在解释一切方面做得很好,因此没有经验的 Laravel 和 React Dev 也能理解发生了什么。它实际上读起来并不多,但显示了一些有趣的特性: https://inertiajs.com/

【讨论】:

    猜你喜欢
    • 2022-07-29
    • 2023-03-12
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    • 2021-03-09
    • 2021-12-19
    • 2017-09-04
    • 2015-05-07
    相关资源
    最近更新 更多