繁体   English   中英

我如何将 map 数据从 state 传到组件 prop?

[英]How do I map data from state to component prop?

首先,我是初学者。 任何帮助,将不胜感激。 所以我使用 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)

控制台日志将数组正确显示为名为“items”的集合,内容为 arrays。如您所见,当响应返回 JSON 时,我尝试将响应字符串化,但我又不知道如何 map 以下是我尝试的代码到 map id,name 等内容作为组件的道具。

              <div>
                  {product.map((product) => {
                          <Product name={product.title} />
                  })}
              </div> 

当我这样做时,我得到错误提示 map 不是 function。我不知道我在这里做错了什么。 我知道我应该在这里使用 redux 或 reducer/context,但我想在使用这些更新之前让它工作。

[.[来自 res:data 的回应][1]][1] [1]: https.//i.stack.imgur.com/auxvl.png

在第一次渲染时,类型的值将是未定义的(在同步代码执行时),尝试将其用作

<div>
   {product?.map((product) => {
   <Product name={product.name} />
   })}
   </div> 

一旦类型的值存在,将确保运行 map(还要确保它是可映射的(是一个数组))

你没有得到你的产品。

从截图中我们可以看出

res.data等于 object,具有一个属性itemsres.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM