I have a functional component which I pass a function addEvent
to, which takes an event parameter. However, when I call the function from props inside a functional component, the function doesn't execute:
const onOk = () => {
const { title, description, start_time, end_time, remind_time } = formStates;
const event = {
title:title[0],
description:description[0],
start_time:start_time.toISOString(),
end_time: end_time.toISOString(),
remind_time: remind_time.toISOString()
}
props.addEvent(event);
props.hideModal();
};
const ModalConductor = props => {
switch(props.modal.currentModal) {
case EVENT_FORM_MODAL:
return <EventsFormModal {...props} title="New Event" addEvent={addEvent}/>
default:
return null;
}
};
Passed Function:
export const addEvent = (event) => dispatch => {
console.log(event);
axios
.post('/api/events/', event)
.then(res => {
dispatch({
type: ADD_EVENT,
payload: res.data
});
}).catch(err => console.log(err));
}
I have read on React docs that passing functions to components requires a this.function = this.function.bind(this);
. However, there is no this
in a functional component and there is no example in the docs. How would I fix this issue? Any help would be appreciated!
in your code ModalConductor is your functional component which takes props as input. you are accessing addEvent directly, instead of props.addEvent.
const ModalConductor = props => {
switch(props.modal.currentModal) {
case EVENT_FORM_MODAL:
return <EventsFormModal {...props} title="New Event" addEvent={props.addEvent}/>
default:
return null;
}
};
also as long as your function definition doesn't contain 'this', you dont have to worry about 'this' binding.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.