【发布时间】:2020-04-12 10:47:42
【问题描述】:
我正在开发我的应用程序。当我试图在 jQuery ajax 调用中绑定我的函数时,它总是说Uncaught TypeError: this.addNewAppointment is not a function
这是我完整的Appointments.jsx 文件:
import React from 'react';
import Appointment from './Appointment';
import AppointmentForm from './AppointmentForm';
import AppointmentsList from './AppointmentsList';
class Appointments extends React.Component {
constructor(props) {
super(props)
this.state = {
appointments: this.props.appointments,
title: 'Put your event title',
appointment_time: 'When would this happen?'
};
this.handleUserInput = this.handleUserInput.bind(this);
this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.addNewAppointment = this.addNewAppointment.bind(this);
}
handleUserInput(obj_value){
this.setState(obj_value);
}
handleFormSubmit(){
let appointment = JSON.stringify({
title: this.state.title,
appointment_time: this.state.appointment_time
});
$.ajax({
url: '/appointments',
type: "POST",
data: appointment,
contentType: 'application/json',
success: function(data){
this.addNewAppointment(data)
}
});
}
addNewAppointment(appointment){
let appointments = React.addons.update(this.state.appointments, { $push: [appointment] } );
this.setState({ appointments: appointments.sort((a, b) => (new Date(a.appointment_time) - new Date(b.appointment_time))
)})
}
render(){
return(
<div>
<AppointmentForm title={this.state.title}
appointment_time={this.state.appointment_time}
onUserInput={this.handleUserInput}
onFormSubmit={this.handleFormSubmit}
/>
<AppointmentsList appointments={this.props.appointments} />
</div>
);
}
}
export default Appointments;
我在构造函数上调用我的绑定:
this.addNewAppointment = this.addNewAppointment.bind(this);
在我尝试调用 addNewAppointment 函数的 ajax 调用中:
$.ajax({
url: '/appointments',
type: "POST",
data: appointment,
contentType: 'application/json',
success: function(data){
this.addNewAppointment(data)
}
});
但是当我尝试添加一个新项目时,我收到了这个错误:
Appointments.jsx:38 Uncaught TypeError: this.addNewAppointment is not a function
at Object.success (Appointments.jsx:38)
at fire (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:3233)
at Object.fireWith [as resolveWith] (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:3363)
at done (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:9841)
at XMLHttpRequest.callback (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:10312)
知道我做错了什么吗?
【问题讨论】:
标签: javascript ruby-on-rails reactjs