[英]How to access data from an item in an array using reactjs state?
我正在嘗試從我的 Django-rest API 獲取的數組中的主 object 獲取數據(id)。
我將使用 id 將其傳遞給 fetch url。
我曾嘗試使用 item.id 但它沒有獲得 id 值。
這是“任務”數組的格式。
[
{
"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`
}
})
我需要訪問任務的 ID。 (在這種情況下,“id”:4)
您需要從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))
}
另一種方法是直接從 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.