React中使用useState钩子关闭模态框时的状态访问问题
问题分析与修复方案
1. 核心问题梳理
你当前的代码存在几个关键问题,导致模态框无法正常访问状态变量、props传递失效:
- 父组件调用模态框时未传递控制显示的
show属性,也没正确传递关闭回调onClose - 父组件传递
closeModal时拼写错误:状态更新函数是setShow,你写成了setshow - 子组件里的URL使用双引号包裹,模板字符串变量
${}无法解析,且子组件没有state变量,应该从props.person中获取对应字段 useEffect直接使用async作为回调,这是React的错误用法(会导致内存泄漏)- 子组件里引用的
props.person.fname在父组件传递的person对象里实际是name: state.fname,字段不匹配 - React元素类名应该用
className而非class,你代码里有多处写错
2. 分步修复代码
第一步:修正父组件的模态框调用
传递show状态控制显示,同时传递关闭回调,修正拼写错误并补全子组件需要的字段:
// 父组件中的状态定义 const [show, setShow] = useState(false); // 父组件中调用模态框的代码 <Modal show={show} onClose={() => setShow(false)} person={{ name: state.fname, fname: state.fname, lname: state.lname, imageId: '1bX5QH6', notificationTitle: 'Regular Appointment', stime: state.stime, date: state.date, timecost: state.timecost, type: state.type, patientid: '999999' }} />
第二步:修正模态框组件的问题
import axios from 'axios'; // 记得导入logo和boxes图片 export const Modal = (props) => { // 从props.person中解构需要的字段,简化代码 const { name, fname, lname, patientid, stime, date, type, timecost } = props.person; // 用反引号包裹模板字符串,正确解析变量 const url = `https://testcf-boisterous-ardvark-pc.mybluemix.net/test/addAppointment?pid=999998&date=${date}&starttime=${stime}:00&timecost=${timecost}&name=${fname},${lname}&reason=${type}`; // 修正useEffect的async用法:内部定义async函数再执行 useEffect(() => { const fetchInitialData = async () => { try { const response = await axios(url); console.log("testing our useeffect"); console.log(response.data); } catch(error) { console.error(error.response || error); } }; fetchInitialData(); }, [url]); // 添加url作为依赖项,确保变量更新时重新请求 // 用props.show控制模态框是否渲染 if (!props.show) { return null; } // 手动调用的请求函数 const handleSubmit = async () => { try { const response = await axios(url); console.log(response.data); } catch(error) { console.error(error.response || error); } }; return ( <div className="modal" onClick={props.onClose}> <div className="background" onClick={e => e.stopPropagation()}> <div> <h4 className="margin-bottom">Saving to Master</h4> <h4 className="margin-top">Confirming Your Booking</h4> <img src={logo} alt="logo image" /> <h2 className="reduce-text">Save and Submit Timeslot</h2> <h4>for <span className="bold underline">{name}</span></h4> <div> <h5>{patientid}</h5> <img src={boxes} alt="Two Double Boxes" /> </div> </div> <div className="modal-footer"> <button className="btn-close" onClick={props.onClose}>Cancel</button> {/* Confirm按钮先提交数据再关闭模态框 */} <button className="btn-submit" onClick={() => { handleSubmit(); props.onClose(); }}>Confirm</button> </div> </div> </div> ); }; export default Modal;
3. 额外注意点
useEffect的依赖数组必须包含所有用到的外部变量(比如url),否则会出现闭包导致的旧值问题- 错误处理时尽量打印完整错误信息,方便排查问题
- 如果需要等待API请求完成后再关闭模态框,可以在
handleSubmit的try块里调用props.onClose()
内容的提问来源于stack exchange,提问作者Chris Gauthier Winnipeg
相关产品推荐
相关产品推荐

