【发布时间】:2017-05-06 03:22:16
【问题描述】:
let user = {
"id":14,
"email":"fryguy@gmail.com",
"first_name":"Fry",
"last_name":"Hamson",
"posts":[ { id: 28,
dog_name: 'Skip',
description: 'yub nub! yub nub!',
image_url: 'https://www.k9ofmine.com/wp-content/uploads/2014/09/ewok-dog-costume.jpg' },
{ id: 29,
dog_name: 'Champ',
description: 'You were my brother! I loved you!',
image_url: 'http://stories.barkpost.com/wp-content/uploads/2014/04/dog-star-wars-costume-12.jpg' },
{ id: 32,
dog_name: 'Baxter',
description: 'Give me treats, you will...',
image_url: 'http://www3.pictures.zimbio.com/mp/r_Mf-uluvPrx.jpg' } ]
我无法从上述代码 sn-p 中检索数据。我已经设置了所有逻辑,但是我无法弄清楚将其放置在我的 React 组件中的哪个位置而不破坏它。这是我的 React 页面,我在 fetch 中注释掉了逻辑。
class Profile extends Component {
constructor(props){
super(props);
this.state = {
names: [],
descriptions: [],
images: []
}
this.getProfileData = this.getProfileData.bind(this)
}
componentDidMount() {
this.getProfileData()
}
getProfileData() {
fetch(`/api/v1/users`, {credentials: 'same-origin'})
.then(response => response.json())
.then(user => {
this.setState({
id: user.id,
firstName: user.first_name,
lastName: user.last_name,
posts: user.posts
// for (i=0; i<user.posts.length; i++) {
// names.push(user.posts[i].dog_name)
// descriptions.push(user.posts[i].description)
// images.push(user.posts[i].image_url)
// }
})
})
}
render() {
return(
<div>
<ProfileTile />
</div>
)
}
}
我知道注释掉的逻辑没有用 setState 正确格式化,因为我已经移动了很多。但是我对如何实现这个迭代感到迷茫。我在 Rails 端使用 active:model:serializers。 提前感谢您的帮助。
【问题讨论】:
标签: ruby-on-rails api reactjs fetch active-model-serializers