如何使用axios获取请求中的数据更新数组,并使用React Hooks进行渲染



我从Todoist 获取活动任务列表

const [activeTasks, setActiveTasks] = useState([]);
useEffect(() => {
axios
.get("https://api.todoist.com/rest/v1/tasks?project_id=111234345", {
headers: {
Authorization: "Bearer xxxAuthorisationCodexxx",
},
})
.then((res) => setActiveTasks(res.data));
}, []);

处理结果。

const [allTasks, setAllTasks] = useState([]);  // flat list of all tasks
const [nestedAllTasks, setNestedAllTasks] = useState([]);  // Nested list of all tasks
useEffect(() => {
let tasks = [];
activeTasks.map((task) =>
tasks.push({
id: task.id,
parent_id: task.parent_id,
content: task.content,
priority: task.priority,
comments: [],
complete: false,
})
);

setAllTasks(tasks);
}, [activeTasks, labels]);

然后,我尝试在allTasks上迭代并添加注释,每个注释都需要一个基于任务id的获取请求,我已将其封装在getComments函数中。

const getComments = useCallback(async (task_id) => {
const comments = await axios.get(
`https://api.todoist.com/rest/v1/comments?task_id=${task_id}`,
{
headers: {
Authorization: "Bearer xxxAuthorisationCodexxx",
},
}
);
return comments;
}, []);
useEffect(() => {
let tasks = [...allTasks];  // shallow copy allTasks
const getAllComments = () => {
tasks.map(async (task) => {  // loop over all tasks
await getComments(task.id)  // get comments for specific task
.then((res) => (task.comments = res.data))  // add to comments property
});
};
getAllComments()

setAllTasks(tasks);  // update allTasks with new array including comments
}, [getComments, allTasks]);

我希望allTasks现在有一个来自提取请求的注释,即

{
id: 1,
parent_id: undefined,
content: "Some content",
priority: 2,
labels: ["thing", "other"],
comments: [{id: 12, content: "comment1"}, {id: 22, content: "comment2"}]
complete: false,
}

根据的要求呈现功能

return (
<div>
{nestedAllTasks.length !== 0 ? (
nestedAllTasks.map((task) => {
return <Task key={task.id} task={task} colours={colours} />;
})
) : (
<p>Loading active tasks...</p>
)}
</div>
);

任务组件

export default function Task() {
return (
<div key={task.id}>  
<div>{task.content}</div>
<div>
{task.comments
? task.comments.map((comment) => <div>{comment.content}</div>)
: null}
</div>
</div>
</div>
);
}

当我console.log(allTasks)时,我有时会得到我所期望的,但这永远不会在屏幕上呈现。

您在上一次使用效果中使用了然后等待。这是不对的。您应该将wait的返回值保存在一个变量中。

tasks.map(async (task) => {  // loop over all tasks
let  res = await getComments(task.id) 
task.comments = res.data 
});
};

相关内容

  • 没有找到相关文章

最新更新