我昨天问了这个问题,得到了一个我理解并试图实现的答案。在父组件中调用状态变量后,在访问模式中的状态变量时遇到问题。
下面是我设置的状态变量:
const [show, setShow] = useState(false);
下面是我如何在父组件中调用MODEL,下面是我MODEL组件以及如何在MODEL道具中使用closeModal
函数:
export const Modal = (props) => {
const test = props.person.name;
const fname = props.person.fname;
const patientid = props.person.patientid;
//this function should be in the props array, but its not there.
const setshow = props.closeModal;
const url = "https://testcf-boisterous-ardvark-pc.mybluemix.net/test/addAppointment?pid=999998&date=${state.date}&starttime=${state.stime}:00&timecost=00:09:00&name=${state.fname},${state.lname}&reason=${state.type}";
useEffect(async () => {
try {
const response = await axios(url);
const data = response.data;
console.log("testing our useeffect");
console.log(data);
}
catch(error) {
console.log(error.response);
}
}, []);
if (!props.show) {
return null
}
const fetchData = async () => {
//console.log("calling fetchData");
try {
const response = await axios(url);
const data = response.data;
console.log(data);
}
catch(error) {
console.log(error.response);
}
}
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 class="reduce-text">Save and Submit Timeslot</h2>
<h4>for <span class="bold underline">{test}</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>
<button className="btn-submit" onClick={props.onClose}>Confirm</button>
</div>
</div>
</div>\
)
};
export default Modal;
我这样使用情态动词:\
<Modal
closeModal={setshow}
person={{
name: state.fname,
imageId: '1bX5QH6',
notificationTitle: 'Regular Appointment',
time: state.stime,
adate: state.date,
timecost: state.timecost,
reason: state.type,
patientid: '999999'
}}
/>
2条答案
按热度按时间w3nuxt5m1#
正如阿明在他们的回答中指出的那样,你把州设错了。
您希望将一个函数传递给
Modal
组件,Modal
稍后将在它想要关闭时*调用该函数,从而有效地将状态冒泡到父组件。您还将把show
的当前值传递给modal,这样它就知道是否应该显示。这就是如何将其传递给您的
Modal
:然后,在你的模式中,不要有
const setshow = props.closeModal
,你不需要那个。在您的模式组件中,您可以在
!props.show
时提前返回,就像您正在做的那样:然后,要解决您的问题,只需:
因此,它将调用传递给它的函数,该函数(在本例中)将更新父对象中的状态。这是我使用过的所有modal库都倾向于使用的模式。它很强大,因为您可以在调用模式时将其传递给
closeModal
中更复杂的函数,允许您在关闭模式时轻松地采取其他操作,而不仅仅是更新显示状态。现在这将会起作用,因为`pros.closeMoal
toe950272#
“const setshow=pros.closeModal”这不是更新状态的正确方式。
尝试setShow(pros.closeModal)。