[英]API Json data not being rendered by map() in my react app
My array of API generated "todo" objects.我的 API 数组生成了“待办事项”对象。
That is console logged, but i have also saved it as a variable, todosData.那是控制台记录的,但我也将它保存为变量 todosData。 Now this variable used to be the same format( array of objects with id, title, completed ) but my hardcoded data.
现在这个变量曾经是相同的格式(带有 id、title、completed 的对象数组)但是我的硬编码数据。 I rendered this with components as my app is made with react.
我用组件渲染了这个,因为我的应用程序是用 react 制作的。 This is the code for it:
这是它的代码:
import React from "react";
import TodoItem from "./TodoItem";
import todosData from "./TodosData";
// Container for every todo object
export default function Todos() {
const todoItemArray = todosData.map((todo) => {
return <TodoItem title={todo.title} key={todo.id} completed={todo.completed} />;
});
return <div>{todoItemArray}</div>;
}
Now as you can see i havent even changed the array name when i switched from hardcoded data to api data.现在您可以看到,当我从硬编码数据切换到 api 数据时,我什至没有更改数组名称。 Both were an array of objects, as i mentioned.
正如我所提到的,它们都是一组对象。 Just this map method is rendered 0 components to my website.
只是这个 map 方法在我的网站上呈现了 0 个组件。 Before it rendered all ( when i hardcoded the values ).
在它呈现所有之前(当我对值进行硬编码时)。 Im completely confused.
我完全糊涂了。
This is the fetch() method to get the data.这是获取数据的 fetch() 方法。 Even though my console.log shows that isnt the problem:
即使我的 console.log 显示这不是问题:
let todosData = [];
fetch("https://jsonplaceholder.typicode.com/posts/")
.then((res) => res.json())
.then((data) => todosData.push(...data))
.then(() => console.log(todosData));
export default todosData;
You can't just store your data in a variable.您不能只将数据存储在变量中。 React does not know when you mutate it.
React 不知道你什么时候改变它。 You need to use component state so that react knows when to re-render your component.
您需要使用组件 state以便 react 知道何时重新渲染您的组件。 Also the place to fetch data is in an effect:
获取数据的地方也有效:
export default function Todos() {
const [todos, setTodos] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts/")
.then(res => res.json())
.then(data => setTodos(data))
}, []);
return (
<div>
{todos.map(todo => (
<TodoItem title={todo.title} key={todo.id} completed={todo.completed} />
)}
</div>;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.