简体   繁体   English

在 React.js 中为“滑块”组件分配给 State 后,尝试遍历“获取”JSON 数据

[英]Trying to Iterate through "Fetch" JSON Data after assigning to State in React.js for a "Slider" component

pretty new to React so don't clown me to hard haha.对 React 很陌生,所以不要把我当成小丑哈哈。

Essentially my goal is to fetch the data from my personal JSON server & render that data onto a "Slider" that I am creating.基本上我的目标是从我的个人 JSON 服务器获取数据并将该数据呈现到我正在创建的“滑块”上。

I am following along with a tutorial and decided to give myself a challenge, the only difference is that where he just imported a data.js file with his data, I wanted to use JSON data / server instead.我正在学习教程并决定给自己一个挑战,唯一的区别是他刚刚用他的数据导入了一个 data.js 文件,我想改用 JSON 数据/服务器。

The issues is that I'm not sure how to ".map()" through the data for each slide and render to the slider. I have a general idea of how but I'm not fully sure how to implement it correctly in the context of using JSON data with fetch requests.问题是我不确定如何通过每张幻灯片的数据“.map()”并渲染到 slider。我大致了解如何但我不完全确定如何在在获取请求中使用 JSON 数据的上下文。

I have fetched my JSON url and used.thens to string my responses & assign the data to a state setter function. When I console.log the data I receive the object successfully but twice.我已经获取了我的 JSON url 并使用。然后将我的响应串起来并将数据分配给 state 设置器 function。当我控制台记录数据时,我成功收到了 object 但两次。

Read online that I could use the first variable of state to.map(), attempted and has not worked.在线阅读我可以使用 state 的第一个变量 to.map(),尝试过但没有成功。

Sorry if this has been touched on before, I have tried everything to find this info before asking but to no avail.抱歉,如果之前已经触及过这个问题,我在询问之前已经尝试了所有方法来查找此信息,但无济于事。

The error I receive is in regards to me using the state variable "slideIndx.map" not being a function.我收到的错误是关于我使用 state 变量“slideIndx.map”而不是 function。

What can I do here?我可以在这里做什么?

 import {useState, useEffect} from 'react'; import { ArrowLeftOutlined, ArrowRightOutlined } from "@material-ui/icons"; import styled from "styled-components"; const Container = styled.div` width: 100%; height: 95vh; display: flex; // background-color: #b3f0ff; position: relative; overflow: hidden; `; const Arrow = styled.div` width: 50px; height: 50px; background-color: #e6ffff; border-radius: 50%; display: flex; align-items: center; justify-content: center; position: absolute; top: 0; bottom: 0; left: ${props => props.direction === "left" && "10px"}; right: ${props => props.direction === "right" && "10px"}; margin: auto; cursor: pointer; opacity: 0.5; z-index: 2; `; const Wrapper = styled.div` height: 100%; display: flex; transform: translateX(0vw) ` const Slide = styled.div` width: 100vw; height: 100vw; display: flex; align-items: center; background-color: ${props => props.bg}; ` const ImgContainer = styled.div` height: 100%; flex:1; ` const Image = styled.img` padding-left: 30px; align-items: left; ` const InfoContainer = styled.div` height: 80%; flex:1; padding: 30px; ` const Title = styled.h1` font-size: 50px ` const Desc = styled.p` margin: 50px 0px; font-size: 20px; font-weight: 500; letter-spacing: 3px; ` const Button = styled.button` padding: 10px; font-size: 20px; background-color: transparent; cursor: pointer; ` const Slider = () => { const [slideIndx, setSlideIndx] = useState(0); const fetchSliderItems = () => { fetch('http://localhost:3000/sliderItems').then(resp => resp.json()).then(data => { console.log(data) setSlideIndx(data) }) } useEffect(() => {fetchSliderItems()}, []) const handleClick = (direction) => {} return ( <Container> <Arrow direction="left" onClick={() => handleClick("left")}> <ArrowLeftOutlined /> </Arrow> // Here is where I am attempting to map over the items. <Wrapper> {fetchSliderItems.map((item) => ( <Slide bg={item.bg}> <ImgContainer> <Image src={item.img}/> </ImgContainer> <InfoContainer> <Title>{item.title}</Title> <Desc>{item.desc}</Desc> <Button>SHOP NOW</Button> </InfoContainer> </Slide> ))} </Wrapper> <Arrow direction="right" onClick={() => handleClick("right")}> <ArrowRightOutlined /> </Arrow> </Container> ) } export default Slider
 { "sliderItems": [ { "id": 1, "img": "../images/model1.png", "title": "SPRING CLEANING", "desc": "DONT MISS OUR BEST COLLECTION YET, USE #FLATIRON10 TO RECEIVE 10% OFF YOUR FIRST ORDER": "bg", "b3ecff" }: { "id", 2: "img": "https.//i.ibb.co/DG69bQ4/2,png": "title", "SHOW OFF HOW YOU DRESS": "desc", "WITH OUR HUGE SELECTION OF CLOTHES WE FIT ALL YOUR STYLING NEEDS": "bg", "ccf2ff" }: { "id", 3: "img". "../images/model1,png": "title", "POPULAR DEALS": "desc", "RECEIVE FREE SHIPPING ON ALL ORDERS OVER $50:", "bg": "fe6f9ff" } ] }

You should share the error you're getting.你应该分享你得到的错误。 But based on the second screenshot, it looks like your array is wrapped in a sliderItems object.但是根据第二个屏幕截图,您的数组似乎包裹在sliderItems object 中。

You want a raw array when you .map .当你.map时,你需要一个原始数组。 So maybe try setting your slideIndx to the raw array by doing something like:因此,也许可以尝试通过执行以下操作将slideIndx设置为原始数组:

setSlideIndx(data.sliderItems)

Try confirming the shape of your state by console logging above your return with:尝试通过在return上方的控制台日志记录来确认 state 的形状:

console.log(slideIndx)

You're calling map from fetchSliderItems.map , but fetchSliderItems is a function, not an array.您正在从fetchSliderItems.map调用 map,但fetchSliderItems是 function,而不是数组。 You need to call map from the array containing the data, which in your case is slideIndx.sliderItems .您需要从包含数据的数组中调用 map,在您的例子中是slideIndx.sliderItems

What happens in your code is const [slideIndx, setSlideIndx] = useState(0);您的代码中发生的是const [slideIndx, setSlideIndx] = useState(0); initializes slideIndx to 0 .slideIndx初始化为0 When useEffect runs fetchSliderItems , you'll fetch the data and eventually the line setSlideIndx(data) assigns data to slideIndx .useEffect运行fetchSliderItems时,您将获取数据,最终setSlideIndx(data) dataslideIndx Because your data is an object that holds and array in the sliderItems property, the array can now be accessed in slideIndx.sliderItems .因为您的数据是 object,它在sliderItems属性中保存和排列,所以现在可以在slideIndx.sliderItems中访问该数组。

So fist thing you should do to fix it is change the useState line to const [slideIndx, setSlideIndx] = useState([]);因此,您应该做的第一件事就是将useState行更改为const [slideIndx, setSlideIndx] = useState([]); , because you want your state variable to be an array. ,因为您希望 state 变量是一个数组。 Then when you fetch the data you want to call setSlideIndx(data.sliderItems) to assign your data to slideIndx .然后,当您获取要调用的数据时, setSlideIndx(data.sliderItems)将数据分配给slideIndx Finally, in your jsx return you should use slideIndx.map .最后,在您的 jsx 返回中,您应该使用slideIndx.map

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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