为什么状态不在React中进行更新?

发布于 2025-01-18 06:49:30 字数 1523 浏览 0 评论 0原文

我在React中有一个Alice-Carousel,我可以从API中获取项目。从API获取数据后,我正在更新旋转木马的项目阵列,但正在获取项目的价值,如未定义。加密固定是防止支撑的背景。

import React from 'react'
import { useEffect ,useState} from 'react';
import { CryptoState } from '../CryptoContext'
import { TrendingCoins } from '../api';
import axios from 'axios'
import AliceCarousel from 'react-alice-carousel';
import {Link} from 'react-router-dom'

const Carousel = () => {
    const [trending,setTrending] = useState([]);
    const {currency,setCurrency} = CryptoState();
  
    useEffect(() => {
      const {data}= axios.get(TrendingCoins(currency));
      setTrending(data);
    },[currency,trending])
    
    // 0 pe 2 items dikhane hai, 512 size pe 4 items dikhane hai,
    // thats all about responsiveness.

    const responsives = {               
      0: {
        items: 2
      },
      512: {
        items: 4
      }
    }

    const items= trending.map((coin) => {
      return (
        <>
          <Link to={`/coins/${coin.id}`}/>
          <img 
             className="carouselImages"
             src={coin?.image}
             height="80"
             style={{marginBottom:10}}
          />
        </>
      )
    })

    return (
      <AliceCarousel
       infinite
       mouseTracking
       autoPlayInterval={1000}
       animationDuration={1500}
       disableDotsControls
       responsive={responsives}                     
       autoPlay
       items={items}
      />
    )
}

export default Carousel

I have a Alice-Carousel in react where I am getting the items from an API.After fetching the data from API , I am updating the items array for the carousel but am getting the value of items as undefined. CryptoState is the context to prevent prop-drilling.

import React from 'react'
import { useEffect ,useState} from 'react';
import { CryptoState } from '../CryptoContext'
import { TrendingCoins } from '../api';
import axios from 'axios'
import AliceCarousel from 'react-alice-carousel';
import {Link} from 'react-router-dom'

const Carousel = () => {
    const [trending,setTrending] = useState([]);
    const {currency,setCurrency} = CryptoState();
  
    useEffect(() => {
      const {data}= axios.get(TrendingCoins(currency));
      setTrending(data);
    },[currency,trending])
    
    // 0 pe 2 items dikhane hai, 512 size pe 4 items dikhane hai,
    // thats all about responsiveness.

    const responsives = {               
      0: {
        items: 2
      },
      512: {
        items: 4
      }
    }

    const items= trending.map((coin) => {
      return (
        <>
          <Link to={`/coins/${coin.id}`}/>
          <img 
             className="carouselImages"
             src={coin?.image}
             height="80"
             style={{marginBottom:10}}
          />
        </>
      )
    })

    return (
      <AliceCarousel
       infinite
       mouseTracking
       autoPlayInterval={1000}
       animationDuration={1500}
       disableDotsControls
       responsive={responsives}                     
       autoPlay
       items={items}
      />
    )
}

export default Carousel

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浊酒尽余欢 2025-01-25 06:49:31
useEffect(()=>{
const getData = async () => {
    try{
        const {data} = await axios.get(TrendingCoins(currency));
        setTrending(data);
    }catch{}
}
getData()
}, [currency, trending])

您没有等待响应,也可以在使用效率箭头函数

编辑中写async。 : https://devtrium.com/posts/posts/ashync-functs-functions-useeeeefect-yeefect-functions-useeeefect

useEffect(()=>{
const getData = async () => {
    try{
        const {data} = await axios.get(TrendingCoins(currency));
        setTrending(data);
    }catch{}
}
getData()
}, [currency, trending])

you are not waiting for the response, also you can just write async in useEffect arrow function

edit. : https://devtrium.com/posts/async-functions-useeffect

左岸枫 2025-01-25 06:49:31
      const {data}= axios.get(TrendingCoins(currency));

问题是Axios。Get是一个异步调用,因此基本上您不在等待结果,您可以异步/等待或承诺

    useEffect(async ()=>{
      const response = await axios.get(TrendingCoins(currency));
      setTrending(response.data);
    },[currency,trending])
      const {data}= axios.get(TrendingCoins(currency));

the problem is axios.get is a async call so basically your are not waiting for its result, you could async/await or promises

    useEffect(async ()=>{
      const response = await axios.get(TrendingCoins(currency));
      setTrending(response.data);
    },[currency,trending])
念三年u 2025-01-25 06:49:31

Axios是异步的,这意味着该应用需要等待数据传递。这样做的方法之一是使用Thenables。

useFect()依赖esecies存在一些问题。如果您将趋势作为依赖关系,则会有一个无限循环,可能会使浏览器崩溃。这是因为usestate挂钩重新呈现组件并更改状态和useffect当依赖关系值更改时触发。

返回中,您还需要进行更改。如果该应用没有可用数据,则无法显示。为了解决这个问题,我们需要使用条件语句。

看看

import React from 'react'
import { useEffect ,useState} from 'react';
import { CryptoState } from '../CryptoContext'
import { TrendingCoins } from '../api';
import axios from 'axios'
import AliceCarousel from 'react-alice-carousel';
import {Link} from 'react-router-dom'

const Carousel = () => {
    const [trending,setTrending]=useState([]);
    const {currency,setCurrency}=CryptoState();
  
    useEffect(()=>{
      axios.get(TrendingCoins(currency))
      .then((data) => {
          setTrending(data)
      })
      .catch((error) => {
          console.log(error)
      })
     
    },[currency])

    const responsives={         //0 pe 2 items dikhane hai, 512 size pe 4 items dikhane hai,thats all about responsiveness.
      0:{
        items:2,
      },
      512:{
        items:4,
      }
    }

    const items = trending.map((coin)=>{
      return (
        <>
        <Link to={`/coins/${coin.id}`}/>
        <img className="carouselImages"
        src={coin?.image}
        height="80"
        style={{marginBottom:10}}
        />
        </>
      )
    })

  if(trending === undefined) return (<p>Loading data....</p>)
  else return (
    <AliceCarousel
    infinite
    mouseTracking
    autoPlayInterval={1000}
    animationDuration={1500}
    disableDotsControls
    responsive={responsives}                 //responsive is to generate responsiveness....
    autoPlay
    items={items}
    />
  )
}

export default Carousel

Axios is asynchronous meaning the App needs to wait for the data to be delivered. One of the way to do this is by using Thenables.

There are some problems with the useEffect() dependecies. If you add trending as a dependency there will be an infinite loop that will probable make the browser crash. This is because the useState hook re-renders the component and changes the state and useEffect triggers when a dependency value changes.

In the return you also need to make changes. If the App does not have the available data, it cannot show it. To solve this we need use conditional statements.

Take a look

import React from 'react'
import { useEffect ,useState} from 'react';
import { CryptoState } from '../CryptoContext'
import { TrendingCoins } from '../api';
import axios from 'axios'
import AliceCarousel from 'react-alice-carousel';
import {Link} from 'react-router-dom'

const Carousel = () => {
    const [trending,setTrending]=useState([]);
    const {currency,setCurrency}=CryptoState();
  
    useEffect(()=>{
      axios.get(TrendingCoins(currency))
      .then((data) => {
          setTrending(data)
      })
      .catch((error) => {
          console.log(error)
      })
     
    },[currency])

    const responsives={         //0 pe 2 items dikhane hai, 512 size pe 4 items dikhane hai,thats all about responsiveness.
      0:{
        items:2,
      },
      512:{
        items:4,
      }
    }

    const items = trending.map((coin)=>{
      return (
        <>
        <Link to={`/coins/${coin.id}`}/>
        <img className="carouselImages"
        src={coin?.image}
        height="80"
        style={{marginBottom:10}}
        />
        </>
      )
    })

  if(trending === undefined) return (<p>Loading data....</p>)
  else return (
    <AliceCarousel
    infinite
    mouseTracking
    autoPlayInterval={1000}
    animationDuration={1500}
    disableDotsControls
    responsive={responsives}                 //responsive is to generate responsiveness....
    autoPlay
    items={items}
    />
  )
}

export default Carousel

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文