You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Rails旅行规划App:渲染指定Trip关联的Place

解决Rails+React旅行应用中Trip关联Place的渲染问题

方案一:后端过滤(推荐,减少不必要的数据传输)

修改Rails后端代码

在PlacesController的index方法中,通过请求参数接收当前Trip的ID,只返回该Trip关联的Place:

def index
  if params[:trip_id].present?
    @places = Place.where(trip_id: params[:trip_id])
  else
    @places = Place.all
  end
  render json: @places.as_json
end

修改React前端代码

  1. 新增状态存储当前打开的Trip(根据你实际打开Modal的逻辑调整触发时机):
const [currentTrip, setCurrentTrip] = useState(null);

// 打开Modal时记录目标Trip
const handleShowTrip = (trip) => {
  setCurrentTrip(trip);
  setIsTripShowVisable(true);
};
  1. 修改获取Place的逻辑,请求时携带当前Trip的ID:
const handleIndexPlaces = (tripId) => {
  const url = tripId ? `http://localhost:3000/places.json?trip_id=${tripId}` : "http://localhost:3000/places.json";
  axios.get(url).then((response) => {
    setPlaces(response.data);
  });
};

// 打开Modal时触发请求,仅获取当前Trip的Place
const handleShowTrip = (trip) => {
  setCurrentTrip(trip);
  handleIndexPlaces(trip.id);
  setIsTripShowVisable(true);
};
  1. 保持Modal与TripsShow组件的传递逻辑不变即可。

方案二:前端过滤(无需修改后端)

如果暂时不想调整后端逻辑,可以在前端拿到所有Place后,根据当前Trip的ID过滤出关联地点:

修改React前端代码

  1. 存储当前打开的Trip:
const [currentTrip, setCurrentTrip] = useState(null);

const handleShowTrip = (trip) => {
  setCurrentTrip(trip);
  setIsTripShowVisable(true);
};
  1. 传递给TripsShow组件时,过滤出属于当前Trip的Place:
<Modal show={isTripShowVisable} onClose={handleHideTrip}>
  <TripsShow 
    places={places.filter(place => place.trip_id === currentTrip.id)} 
    trips={trips} 
  />
</Modal>
  1. TripsShow组件无需修改,直接使用过滤后的数组渲染即可。

内容的提问来源于stack exchange,提问作者Robyn S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 23:18:31