[英]How do I map data from state to component prop?
To start with I'm a beginner.首先,我是初学者。 Any help would be appreciated.
任何帮助,将不胜感激。 So I'm getting my data from mongoDB atlas using node+express API. I'm successfull at getting the array to show up in console log using following code.
所以我使用 node+express API 从 mongoDB atlas 获取我的数据。我使用以下代码成功地让数组显示在控制台日志中。
const [product, setProduct] = useState();
const url = "http://localhost:5000/api/items";
useEffect(() => {
axios.get(url).then((res) => {
setProduct(res.data);
// setProduct(
// JSON.stringify({
// title: setProduct.title,
// price: setProduct.price,
// image: setProduct.image,
// details: setProduct.details,
// })
// );
})
}, [url])
console.log(product)
The console log displays the array properly as collection named 'items' with content of arrays. As you can see I tried to stringify the response as the response returns JSON but again I didn't know how to map Following is the code where I tried to map the contents like id, name etc as props to component.控制台日志将数组正确显示为名为“items”的集合,内容为 arrays。如您所见,当响应返回 JSON 时,我尝试将响应字符串化,但我又不知道如何 map 以下是我尝试的代码到 map id,name 等内容作为组件的道具。
<div>
{product.map((product) => {
<Product name={product.title} />
})}
</div>
When I do this I get error that the map is not a function. I don't know what I'm doing wrong here.当我这样做时,我得到错误提示 map 不是 function。我不知道我在这里做错了什么。 I know I'm supposed to use redux or reducer/context here but I want to get this to work before updating it with those.
我知道我应该在这里使用 redux 或 reducer/context,但我想在使用这些更新之前让它工作。
[.[Response from res:data][1]][1] [1]: https.//i.stack.imgur.com/auxvl.png [.[来自 res:data 的回应][1]][1] [1]: https.//i.stack.imgur.com/auxvl.png
On the first render the value for types will be undefined ( on sync code execution ), try using it as在第一次渲染时,类型的值将是未定义的(在同步代码执行时),尝试将其用作
<div>
{product?.map((product) => {
<Product name={product.name} />
})}
</div>
? ? will make sure to run map once value for types is there ( also make sure it is mappable ( is an array ))
一旦类型的值存在,将确保运行 map(还要确保它是可映射的(是一个数组))
you didnt get yours products.你没有得到你的产品。
As we can see from screenshot从截图中我们可以看出
res.data
equal to object with one property items
: res.data
= {items: []}
and we need to take/access to these items res.data
等于 object,具有一个属性items
: res.data
= {items: []}
我们需要获取/访问这些项
use this: setProducts(res?.data?.items || [])
使用这个:
setProducts(res?.data?.items || [])
const [products, setProducts] = useState();
useEffect(() => {
axios.get(url).then((res) => {
setProducts(res?.data?.items || []);
})
}, [url])
<div>
{products?.map((product) => {
<Product name={product.title} />
})}
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.