将对象数组映射到状态

时间:2018-07-06 06:13:03

标签: javascript reactjs

我有一个API以这种形式给出错误响应 enter image description here

在reactJS中,我可以使用this.props.errors传递参数给子组件,但是现在我想按如下所示将this.props.errors映射到子组件

state = {
 slug: '', 
 name: '', 
 address_1: '', 
 address_2: '', 
 city: '', 
 state: '', 
 postal_code: '', 
 country_code: '', 
 phone_number: '',
}

的意思是,我希望将error参数的元素放在每个元素的子组件状态中。我该怎么办?

1 个答案:

答案 0 :(得分:0)

根据您的要求保存您的响应以进行定制。按照代码段。将其保存为状态,然后将此状态传递给孩子。通过使用componentWillReceiveProps更新子状态。

示例:working Code with React

let response = {
      slug: ['slug required'],
      name: ['name'],
      address_1: ['address_1'],
      address_2: ['address_2'],
      city: ['city'],
      state: ['state'],
      postal_code: ['postal_code'],
      country_code: ['country_code'],
      phone_number: ['phone_number ']
    } 
    const keys = Object.keys(response)
    keys.map((m)=>{
      response[m] = Array.isArray(response[m]) ? response[m][0] : response[m]
    })
    console.log("customed response",response)