I have facing an issue in React JS data parsing, i want to get start_date
from JSON data
我的密码
//fetch appointment data
componentDidMount() {
axios.get(`http://localhost/v1/appointments`)
.then(res => {
const appointmentdata = res.data;
console.log(appointmentdata); //result
this.setState({ appointmentdata });
})
}
反应成分:
<div className="col-lg-3">
{this.state.appointmentdata.map(data => <p>{data.start_date}</p>) }
</div>
错误 未处理的拒绝(TypeError):this.state.appointmentdata.map不是函数
result console.log(appointmentdata)
<div id="root" style="border: 1px solid red; padding : 25px; width: 800px;">This is 'root' div.</div>
-->
[{"id":"1","start_date":"2020-05-09 15:30:00","end_date":"2020-05-09 16:00:00", "cust_email":"admin@gmail.com"},{"id":"2","start_date":"2020-05-09 00:00:00","end_date":"2020-05-09 00:30:00","cust_full_name":"mubeen","cust_email":""}]
我尝试过,但是没有用
this.setState({ appointmentdata: JSON.parse (appointmentdata.replace ("Array", ""))});
How can i get value start_date
.
我该怎么办?有人帮我吗?
在这里你有一个解决方案
First check the length and then start looping it using
.map
.No need of doing
this.setState({ appointmentdata: JSON.parse (appointmentdata.replace ("Array", ""))});
相反,如果您以对象数组形式接收数据,则可以这样做。
One more thing,
appointmentdata
should be defined as[]
this.state { appointmentdata: [] };It looks like your
appointmentdata
has already been parsed, so simply replace:带有:
And it should work as expected. If it's not, maybe on the first render that data hasn't been loaded yet, so it throws an error because
state.appointmentsdate
is undefined.要解决此问题,您可以替换:
带有:
要么:
Or just initialize the
state
withappointmentdata: []
Now it's not working because you are passing an Array to
JSON.parse()
, but it expects a string containing valid JSON: