React中传递给子组件的函数Props无法渲染Option问题排查
问题分析与解决方法
核心问题梳理
initializeTimes函数无返回值:函数内部的map被多余的大括号包裹,导致遍历结果没有被返回,调用该函数时实际返回undefined,所以<option>无法渲染。key属性设置错误:使用整个initialState数组作为<option>的key,不符合React对key的要求(需唯一且对应单个元素)。useReducer初始化逻辑错误:useReducer的第二个参数应传入状态的初始值(这里是时间数组),而非返回JSX的函数,混淆了状态管理与视图渲染的职责。
修正后的代码
父组件(Reservations.js)
import BookingForm from '../components/bookingForm' import { useReducer } from 'react' function Reservations(){ // 初始时间数组作为状态的初始值 const initialState = ["17:00","18:00","19:00","20:00","21:00"] // useReducer的reducer函数,后续可根据action修改时间列表 const updateTimes = (availableTimes, action)=>{ // 示例:根据action类型更新时间 switch(action.type){ case 'UPDATE_TIMES': return action.payload; default: return availableTimes; } } // 初始化时间状态 const [availableTimes, dispatch] = useReducer(updateTimes, initialState); // 生成时间选项的函数,正确返回遍历结果 const renderTimeOptions = () =>{ return availableTimes.map((time) =>{ return <option key={time}>{time}</option> }) } return( <> <Nav/> <header> <div> <h1>Book a table</h1> <h2>Little Lemon</h2> </div> </header> <div> <BookingForm renderTimeOptions={renderTimeOptions} /> </div> <Footer/> </> ) } export default Reservations
子组件(BookingForm.js)
import { useState } from "react"; function BookingForm(props){ // ...其他表单逻辑 return( <div> <label htmlFor="res-time">Choose time</label> <select id="res-time"> {props.renderTimeOptions()} </select> </div> ) }
额外说明
后续若需更新可用时间,只需通过dispatch发送对应action即可,比如:
// 在父组件中触发时间更新 dispatch({type: 'UPDATE_TIMES', payload: ["16:00", "17:00", "18:00"]})
内容的提问来源于stack exchange,提问作者Mr_Yellow7
相关产品推荐
相关产品推荐

