react js和rails在具有活动记录关系的组件上更新状态

react js and rails Updating state on a component with active record relationship

本文关键字:关系 组件 状态 更新 记录 活动 js rails react      更新时间:2023-09-26

我在更新后端react with rails中的组件时遇到问题。我知道问题是什么,但我不知道如何解决它。我会尝试解释,但在此之前我的一些代码,所以我的控制器我正在传递这样的数据:

def index
  @vehicles = Vehicle.all.includes(:customer).as_json(include: {customer: 
  { only: [:name, :lastname, :id]}})
  @customers = Customer.all
  @years = MotorClient.new.years
end

车辆属于客户,我正在传递客户数据。然而,因为我也在创建新的车辆实例,我需要完全传递客户数据,这样我就可以获得列出的所有客户。我将尝试解释而不是放所有的反应代码,因为太冗长了。车辆状态是一个包含客户的对象,如

{key1:value,...{customer:{name:value, lastname:value, id:value}, customer_id:value}

当我输入一辆新车时,我使用一个选择框来获取客户,选择框名称是customer_id,它是外键,这会进入Ajax并更新服务器。问题是,由于我只传递customer_id,而服务器更新就足够了,而react还不够,因此设置react的方式是,在ajax之后,将对象推入客户端的集合数组中,并立即将该数组渲染到索引中。当react尝试更新状态时,我会在控制台上得到这个。

未捕获的类型错误:无法读取未定义的属性"name"

之所以会发生这种情况,是因为在ajax调用中发送的对象不包括客户名称或姓氏,只包括外键。查看新状态的唯一方法是在渲染新车辆时刷新页面,并且它正确地来自服务器。我是否必须创建一个不同的对象来更新前端的状态?

此区域中的未命中是在后端而非前端。Rails create方法没有传递序列化的对象,因此react可以包含客户信息。我接下来要做的是创建一个串行器:

      class VehicleSerializer
       def initialize(vehicle)
         @vehicle = vehicle
       end
      def attributes
         {
           customer: {
                id: @vehicle.customer.id,
                name: @vehicle.customer.name,
               lastname: @vehicle.customer.lastname,
          },
             id: @vehicle.id,
             plate: @vehicle.plate,
             vin: @vehicle.vin,
             year: @vehicle.year,
             make: @vehicle.make,
             model: @vehicle.model,
             engine: @vehicle.engine,
             basevehicleid: @vehicle.basevehicleid
         }
       end
    end

然后我在车辆控制器中使用了这样的创建方法:

    def create
       @vehicle = Vehicle.new(vehicle_params)
      if @vehicle.save
         render json: VehicleSerializer.new(@vehicle).attributes
      else
     render json: @vehicle.errors, status: :unprocessable_entity
     end
    end

这解决了问题,使react可以完成信息。重新渲染修复的原因是,当您点击刷新时,索引操作是正在使用的方法,并且该方法已经序列化。