Это мой json с моего сайта Drupal:
[
{
title: "I believe every human has a finite number of heartbeats. I don't intend to waste any of mine.",
uid: "gestor"
},
{
title: "Man must explore, and this is exploration at its greatest",
uid: "gestor"
}
]
Он состоит из двух элементов, разделенных скобками {} Вот как я пытаюсь использовать Принести в своем компоненте реакции.
componentWillMount(){
// Con fetch me conecto al site de Drupal
fetch('http://rest.dd:8080/all-of-us')
.then(response => response.json())
.then(postPrvSrv => {
// A cada post lo coloco en un array
console.info(postPrvSrv.results)
postPrvSrv.results.forEach(post => {
let data = {
title:post.title,
author:post.uid
}
console.info(data);
// Actualizamos el state para poder renderizar
this.setState({postPrvSrv:this.state.postPrvSrv.concat([data])})
})
})
}
Это мои результаты журнала консоли:
console.info(postPrvSrv.results) = не определено
console.info(data); = Ничего, потому что он сломался в строке 27 .. в для каждого
console.info(this.state.postPrvSrv.length) = 0. Обиус.
Это сообщение об ошибке:
Unhandled Rejection (TypeError): Cannot read property 'forEach' of undefined
И ошибка из консоли:
Uncaught (in promise) TypeError: Cannot read property 'forEach' of undefined



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Если вы напрямую возвращаете массив из конечной точки Durpal, тогда переменная postPrvSrv (в обработчике ответа выборки) будет простым массивом.
Если предположить, что postPrvSrv - это массив, тогда поле .results на postPrvSrv будет undefined.
По этой причине вы получите ошибку «Невозможно прочитать свойство forEach of undefined» - вы пытаетесь вызвать .forEach(..) в поле .results, которое не определено в массиве postPrvSrv.
Чтобы решить эту проблему, попробуйте изменить свой код, как показано в комментариях ниже:
fetch('http://rest.dd:8080/all-of-us')
.then(postPrvSrv => {
console.info(postPrvSrv) // Fix this line to see log of data in console
postPrvSrv.forEach(post => { // Fix this line
let data = {
title:post.title,
author:post.uid
}
console.info(data);
this.setState({postPrvSrv:this.state.postPrvSrv.concat([data])})
})
})