将响应解析为React中的模型对象

huangapple go评论142阅读模式
英文:

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&lt;PersonEntry&gt;(`somehost/personentry`)
          .then(res =&gt; {
            // 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 = &#39;&#39;;
    address: string = &#39;&#39;; 
    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 =&gt; ({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?

huangapple
  • 本文由 发表于 2020年1月7日 00:49:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615968.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定