【问题标题】:Search a table using React and Laravel使用 React 和 Laravel 搜索表
【发布时间】:2021-03-13 15:22:20
【问题描述】:

我正在使用 Laravel 为我的数据库创建一个 api,并使用 React 来呈现/获取数据。如何实现搜索栏和自定义 <select>/range 选择器以及分页来过滤我的数据?

当我使用纯 HTML 时,我使用了完美运行的 datatables.net。除了过滤之外,我还想为 react 实现类似的东西。

【问题讨论】:

    标签: javascript reactjs laravel


    【解决方案1】:

    您需要创建一个 REST API,从那里您将拥有一个索引路由。 https://urdomain.com/api/datas。您可以通过将路由添加到路由文件夹中的 api.php 来完成。

    你的 routes/api.php 看起来像这样:

    <?php
    
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Route;
    use App\Models\Data;
    
    /*
    |--------------------------------------------------------------------------
    | API Routes
    |--------------------------------------------------------------------------
    |
    | Here is where you can register API routes for your application. These
    | routes are loaded by the RouteServiceProvider within a group which
    | is assigned the "api" middleware group. Enjoy building your API!
    |
    */
    
    Route::get('/<datas>', function (Request $request) {
      // The page parameter on the request will tell Laravel
      // What page you are aiming.
      return Data::where('some_column', '=', 'some_value')->paginate(15);
    });
    

    将此设置与您的模型、迁移等...您将开箱即用分页。

    下一步,您需要一个 http 库(例如 fetch 或 axios)与服务器交互,并在您的选择上设置 onChange 以获取数据。

    <select
      onChange={event => {
       fetch(`/api/datas?some_column=${event.target.value}`, {
         headers: { Accept: 'application/json' },
       }).then(response => response.json()).then(json => {
        // this.setState() or setVar, whatever u are doing on ur react app to render
        // the results, or useEffect if using hooks instead
       })
      }}
    ></select>
    

    你的问题很开放,但我希望你能找到你正在寻找的东西的第一步。

    干杯

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 1970-01-01
      • 2017-04-08
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 2021-02-13
      • 2019-02-01
      • 1970-01-01
      相关资源
      最近更新 更多