英文:
Parse response into a model object in React
问题
If you want to "slice" the response into the PersonEntry
object without cherry-picking fields, you can directly assign the res.data
to your PersonEntry
object like this:
componentDidMount() {
axios.get<PersonEntry>(`somehost/personentry`)
.then(res => {
const result: PersonEntry = res.data;
this.setState(result);
})
}
This code will assign all fields from the response (res.data
) to your PersonEntry
object.
英文:
If I have a REST call to some server like this :
componentDidMount() {
axios.get<PersonEntry>(`somehost/personentry`)
.then(res => {
// Can I slice res.data into result ?
const result : PersonEntry = res.data;
this.setState(result)
})
}
And let's say I have a PersonEntry model object :
export class PersonEntry {
name: string = '';
address: string = '';
PersonEntry(){}
}
How can I "slice" the response into this object without cherry picking the fields if the response contains a lot of fields I want to ignore ? Now I will just get all the fields from the response into my PersonEntry object
答案1
得分: 0
是的,您可以仅映射所需的属性:
const result = response.map(obj => ({name: obj.name, address: obj.address}));
所以,在console.log(result)
中,您将只获得您选择的参数。
稍后:
const final: PersonEntry = result;
这样可以吗?
英文:
yes, you can map only properties, which needed:
const result = response.map(obj => ({name: obj.name, address: obj.address}));
So, in console.log(result)
You will have only parameters, which you select.
later:
const final : PersonEntry = result;
It works?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论