我希望在client.jsx
文件中有一些可重用的JS代码导入到React组件(使用webpack构建)。
您可以看到此save()
中的saveWithTwoCallbacks()
,saveWithCallback()
,client.jsx
方法主要是复制粘贴的。 save()
方法相互重用的正确JS语法是什么?
client.jsx文件:
import {browserHistory} from "react-router";
module.exports = {
saveWithTwoCallbacks: function (urlToCall, objectToSave, successCallback, errorCallback) {
$.ajax({
url: urlToCall,
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(objectToSave),
success: function () {
successCallback();
},
error: function (xhr, status, err) {
errorCallback(err.toString());
}
});
},
saveWithCallback: function (urlToCall, objectToSave, callback) {
$.ajax({
url: urlToCall,
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(objectToSave),
success: function () {
callback();
},
error: function (xhr, status, err) {
console.error(xhr, status, err.toString());
}
});
},
save: function (urlToCall, objectToSave, navigateTo) {
$.ajax({
url: urlToCall,
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(objectToSave),
success: function () {
// console.log("saved")
browserHistory.push(navigateTo)
},
error: function (xhr, status, err) {
console.error(xhr, status, err.toString());
}
});
},
}
LoginComponent.jsx文件:
import React from "react";
import {saveWithTwoCallbacks} from "./client";
class LoginComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
data : {
},
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
setFormChangeToStateData(e, this)
}
handleSubmit(e) {
e.preventDefault();
saveWithTwoCallbacks("http://localhost:9000/login", this.state.data, onSuccess, onError);
}
render()......
}
export default LoginComponent;
答案 0 :(得分:0)
save()方法相互重用的正确JS语法是什么?
没什么特别的。函数定义通过function f() { ... }
完成,函数调用通过f()
完成。
在您的情况下,您将$.ajax
电话放在saveWithTwoCallbacks
中,然后从其他电话中调用正确的电话。
为方便起见,请使用named exports:
export function saveWithTwoCallbacks(urlToCall, objectToSave, successCallback, errorCallback) {
// $.ajax ...
}
export function saveWithCallback(urlToCall, objectToSave, callback) {
saveWithTwoCallbacks(
urlToCall,
objectToSave,
callback,
(xhr, status, err) => console.error(xhr, status, err.toString())
);
}
export function save(urlToCall, objectToSave, navigateTo) {
saveWithCallback(urlToCall, objectToSave, () => browserHistory.push(navigateTo));
}
答案 1 :(得分:0)
我只会使用一个功能
saveWithTwoCallbacks: function (urlToCall, objectToSave, successCallback, successCallbackParams, errorCallback, errorCallbackParams) {
$.ajax({
url: urlToCall,
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(objectToSave),
success: function () {
successCallback.apply(null, successCallbackParams);
},
error: function (xhr, status, err) {
errorCallback.apply(null, errorCallbackParams);
}
});
}