如何在 API 中将具有belongs_to关联的嵌套模型呈现为数组?我得到这个:错误:对象作为 React 子项无效

How do I render a nested model with a belongs_to association as an array in my API? I'm getting this: Error: Objects are not valid as a React child

提问人:angiem103 提问时间:12/12/2022 最后编辑:maxangiem103 更新时间:12/12/2022 访问量:62

问:

我正在尝试以这种方式嵌套我的模型:一个用户有许多事件,一个事件属于客户端。我能够让它工作,我的 API 现在看起来像这样。

{
   "id":1,
   "first_name":"Angie",
   "last_name":"Maticorena",
   "phone_number":"(689) 836 1752",
   "email":"[email protected]",
   "events":[
      {
         "id":1,
         "name":"Jackie's 30th Birthday",
         "description":"All black 30th Birthday Party. Event theme is Funeral for her 20s",
         "location":"Suite 542 338 Melania Drive, Lake Deandreland, CO 55541",
         "budget":5000.0,
         "current_cost":3000.0,
         "start_date":"2023-04-25",
         "start_time":"2000-01-01T19:00:00.000Z",
         "end_date":"2023-04-25",
         "end_time":"2000-01-01T23:00:00.000Z",
         "client":{
            "id":1,
            "name":"Gov. Leora Kuphal",
            "phone_number":"(530) 785 4983",
            "email":"[email protected]"
         }
      },
      {
         "id":2,
         "name":"Jessica's and Eduardo's Babyshower",
         "description":"Winnie The Pooh themed baby shower for a baby boy. Parents requested green and beige decorations",
         "location":"Suite 458 170 Maryalice Creek, Lake Khadijah, TX 87148-1671",
         "budget":2000.0,
         "current_cost":600.0,
         "start_date":"2023-05-01",
         "start_time":"2000-01-01T15:00:00.000Z",
         "end_date":"2023-05-01",
         "end_time":"2000-01-01T19:00:00.000Z",
         "client":{
            "id":2,
            "name":"Sen. Leon Franecki",
            "phone_number":"(213) 399 7509",
            "email":"[email protected]"
         }
      }
   ]
}

当我尝试在 React 中渲染用户信息时,出现以下错误:

错误:对象作为 React 子对象无效(找到:带有键 {id, name, phone_number, email} 的对象)。如果要呈现子级集合,请改用数组。 ▶ 22 个堆栈框架被折叠。

(anonymous function)
src/App.js:17
  14 | fetch('/auth')
  15 | .then(r => {
  16 |   if(r.ok){
> 17 |     r.json().then(user => setCurrentUser(user)
     | ^  18 |       )
  19 |   }
  20 | })

如何渲染用户及其嵌套模型?

App.js 组件

import React from "react";
import { Routes, Route } from 'react-router-dom';
import { useState, useEffect } from "react";
import Home from "./components/Home";
import SignUp from "./components/SignUp";
import Login from "./components/Login";
import EditEvent from "./components/EditEvent";

function App() {

  const [currentUser, setCurrentUser] = useState("");
  
  useEffect(() => {
    fetch('/auth')
    .then(r => {
      if(r.ok){
        r.json().then(user => setCurrentUser(user)
          )
      }
    })
  }, [])

  console.log(currentUser)

  function handleLogin(user) {
    setCurrentUser(user)
  }

  function handleSetUser(user) {
    setCurrentUser(user)
  }

  return (
    <div className="App">
      <Routes>
        <Route path="/home" element ={<Home currentUser={currentUser} setCurrentUser={setCurrentUser} />} />
        <Route path="/" element={<Login onLogin={handleLogin}/>} />
        <Route path="/signup" element={<SignUp setUser={handleSetUser}/>} />
        <Route path="/events/:id" element={<EditEvent currentUser={currentUser} />} />
      </Routes>

    </div>
  );
}

export default App;

用户控制器

class UsersController < ApplicationController
    wrap_parameters format: []
    rescue_from ActiveRecord::RecordInvalid, with: :record_invalid_response
    skip_before_action :authorized, only: [:create, :index]

    def index
        users = User.all
        render json: users, include: ['events', 'events.client']
    end

    def create
        user = User.create!(user_params)
        render json: user
    end

    def show
        user = User.find(session[:user_id])
        if user
            render json: user, include: [['events'], 'events.client']
        else
            render json: { error: "Not authorized" }, status: :unauthorized
        end
    end

    private

    def user_params
        params.permit(:username, :password, :first_name, :last_name, :phone_number, :email)
    end

    def record_invalid_response(invalid)
        render json: {error: invalid.record.errors.full_messages}, status: :unprocessable_entity
    end

end

模型

class User < ApplicationRecord
    has_secure_password
    validates :username, uniqueness: true, presence: true, length: { minimum: 6 }
    validates :first_name, :last_name, :phone_number, :email, presence: true

    has_many :clients
    has_many :events
    has_many :vendors

end

class Event < ApplicationRecord
    belongs_to :user
    belongs_to :client
    has_many :event_vendors
    has_many :vendors, through: :event_vendors
end

class Client < ApplicationRecord
    belongs_to :user
    has_many :events


end

序列化程序

class UserSerializer < ActiveModel::Serializer
  attributes :id, :first_name, :last_name, :phone_number, :email


  has_many :events, serializer: UserEventSerializer

end

class EventSerializer < ActiveModel::Serializer
  attributes :id, :user_id, :client_id, :name, :description, :start_date, :end_date, :location, :budget, :current_cost, :start_time, :end_time

  belongs_to :user
  belongs_to :client
  has_many :vendors

end

class ClientSerializer < ActiveModel::Serializer
  attributes :id, :name, :phone_number, :email

  has_many :events
  
end
class UserSerializer < ActiveModel::Serializer
  attributes :id, :first_name, :last_name, :phone_number, :email


  has_many :events, serializer: UserEventSerializer

end

reactjs ruby-on-rails 序列化 模型 嵌套

评论

0赞 LawrenceWebDev 12/12/2022
请包括实际渲染的 React 组件(或至少相关部分)。currentUser
0赞 Vishal Jain 12/12/2022
看看这篇文章 bobbyhadz.com/blog/react-objects-are-not-valid-as-react-child

答: 暂无答案