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前端代码
- 新增状态存储当前打开的Trip(根据你实际打开Modal的逻辑调整触发时机):
const [currentTrip, setCurrentTrip] = useState(null); // 打开Modal时记录目标Trip const handleShowTrip = (trip) => { setCurrentTrip(trip); setIsTripShowVisable(true); };
- 修改获取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); };
- 保持Modal与TripsShow组件的传递逻辑不变即可。
方案二:前端过滤(无需修改后端)
如果暂时不想调整后端逻辑,可以在前端拿到所有Place后,根据当前Trip的ID过滤出关联地点:
修改React前端代码
- 存储当前打开的Trip:
const [currentTrip, setCurrentTrip] = useState(null); const handleShowTrip = (trip) => { setCurrentTrip(trip); setIsTripShowVisable(true); };
- 传递给TripsShow组件时,过滤出属于当前Trip的Place:
<Modal show={isTripShowVisable} onClose={handleHideTrip}> <TripsShow places={places.filter(place => place.trip_id === currentTrip.id)} trips={trips} /> </Modal>
- TripsShow组件无需修改,直接使用过滤后的数组渲染即可。
内容的提问来源于stack exchange,提问作者Robyn S
相关产品推荐
相关产品推荐

