[英]How to access data from an item in an array using reactjs state?
I am trying to get the data (id) from the main object inside an array that I GET from my Django-rest API.我正在尝试从我的 Django-rest API 获取的数组中的主 object 获取数据(id)。
I am going to use the id to pass it into a fetch url.我将使用 id 将其传递给 fetch url。
I have tried to use item.id but it doesn't get the id value.我曾尝试使用 item.id 但它没有获得 id 值。
This is the format of the array of the "task".这是“任务”数组的格式。
[
{
"title": "Task 4",
"description": "Task 4",
"video": "ad12312312",
"done": false,
"steps": [
{
"title": "Task 4 Task 1",
"description": "Task 4 Task 1",
"done": false,
"task_id": 4,
"id": 10
},
{
"title": "Task 4 Task 2",
"description": "Task 4 Task 2",
"done": false,
"task_id": 4,
"id": 11
},
{
"title": "Task 4 Task 3",
"description": "Task 4 Task 3",
"done": false,
"task_id": 4,
"id": 12
}
],
"id": 4
}
]
class Screen extends Component {
constructor() {
super();
this.state = {
task: [],
};
}
componentDidMount() {
AppState.addEventListener('change', this._handleAppStateChange);
fetch('https://url.com/daily-ecommerce/', {
method: 'GET',
headers: {
'Authorization': `Token xxxxx`
}
})
.then( res => res.json())
.then( jsonRes => this.setState({ task: jsonRes }) )
.catch( error => console.log(error))
.then(console.log(this.state.task.id))
fetch(`https://url.com/step/?task_id=${this.state.task.id}`, {
method: 'GET',
headers: {
'Authorization': `Token xxxxx`
}
})
I need to access the ID of the task.我需要访问任务的 ID。 (in this case, the "id":4)
(在这种情况下,“id”:4)
You'd need to get the id in a callback from setState
to ensure it has been set:您需要从
setState
的回调中获取 id 以确保已设置它:
componentDidMount() {
AppState.addEventListener('change', this._handleAppStateChange);
fetch('https://url.com/daily-ecommerce/', {
method: 'GET',
headers: {
'Authorization': `Token xxxxx`
}
})
.then(res => res.json())
.then(jsonRes => this.setState({
task: jsonRes
}, () => {
fetch(`https://url.com/step/?task_id=${this.state.task[0].id}`, {
method: 'GET',
headers: {
'Authorization': `Token xxxxx`
}
})
}))
.catch(error => console.log(error))
}
Another way would be to pass the id directly from the json response:另一种方法是直接从 json 响应中传递 id:
componentDidMount() {
AppState.addEventListener('change', this._handleAppStateChange);
fetch('https://url.com/daily-ecommerce/', {
method: 'GET',
headers: {
'Authorization': `Token xxxxx`
}
})
.then(res => res.json())
.then(jsonRes => {
this.setState({
task: jsonRes
})
fetch(`https://url.com/step/?task_id=${jsonRes[0].id}`, {
method: 'GET',
headers: {
'Authorization': `Token xxxxx`
}
})
})
.catch(error => console.log(error))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.