problem description
problems encountered in dealing with data formats during interaction with the background.
the environmental background of the problems and what methods you have tried
for example: a list
is sent to the background in the following format
list: [
{
id: 10086,
firstName: "",
lastName: "",
birth: 1546072820279,
age: 11,
sex: 0,
//
...
},
...
]
then, I want to preprocess the data for the following two reasons:
-
Before rendering
- on the page, you need to do data processing on some items of in data.
- prevent backend students from modifying fields, such as id-> userId, if it is not handled uniformly in the model layer, then later maintenance is very troublesome. You need to find id, one by one in the page and replace it with userId .
my idea is to create a separate model.js to handle these data preprocessing uniformly.
method 1: class
// model.js
class Person{
constructor(props){
// data Question1: Object.create(props)?
Object.keys(props).forEach(prop => {
this[prop] = props[prop];
});
// /
this.name = props.firstName + props.lastName;
this.birthDate = new Date(props.birth);
// 0 1
this.sex = props.sex === 0 ? "" : ""
}
//
// id
getPhone(){
fetch(xxx, { id: this.id }).then(...)
}
}
// /formatlist
export const formatList = list => list.map(item => new Person(item));
method 2: agent
// model.js
const personHandler = {
get(target, property){
switch (property) {
case "name":
return target.firstName + target.lastName;
case "birthDate":
return new Date(target.birth);
case "sex":
return target.sex === 0 ? "" : "";
// 1
// Question 2 targettarget.getPhone = function(){...} target
default: return target[property];
}
}
};
export const formatList = list => list.map(item => new Proxy(item, personHandler));
conclusion
for reason 1: we extract the preprocessing of this data (independent of the business logic) from the business component / logic to make the business component / logic handle the business more purely.
for reason 2: if the back-end classmate says to change id to userId, I just need to add a line of code in class or proxy to
method 1: this.id = props.userId
, method 2: case "id": return target.userId
question : which of the question1 and 2.
question3: methods 1 or 2 in the comments is more suitable for this scenario. Ask the bosses for help in comparative analysis.
Review
when dealing with such scenarios in business requirements, a corresponding formatXXXData (XXX) {/ / function that processes XXX map and then return the value}
is added to tools.js
. This doesn"t feel very intuitive, so I"m considering whether a model.js
file should be added to handle these data formatting and some business logic (such as getPhone ()
) in a form similar to class Person
above.
but will this increase memory overhead? After all, you need to instantiate all the dataList returned by the backend, setting a lot of properties and methods.