简体   繁体   English

在 React 功能组件中调用异步方法

[英]Calling async method in React functional component

I have a question about a good way to solve this problem I have in React.我有一个关于解决我在 React 中的这个问题的好方法的问题。 I need to gather currencies from my own API that I've created, that works perfectly and I iterate it in my return statement of the React component.我需要从我自己创建的 API 中收集货币,它运行良好,我在 React 组件的 return 语句中对其进行了迭代。 When iterating, I want to use the "item.pairs" data to use as an argument for a method call (async method) to get price information and render it.迭代时,我想使用“item.pairs”数据作为方法调用(异步方法)的参数来获取价格信息并呈现它。 How can this be accomplished?如何实现?

I added a method getCurrencyData, I tried calling that in the return statement inside the loop, but it will not work, and I have searched for this and it's not possible to do that in that way.我添加了一个方法 getCurrencyData,我尝试在循环内的 return 语句中调用它,但它不起作用,我已经搜索过这个方法,但不可能这样做。 So how can I do this?那么我该怎么做呢?

The used code is below:使用的代码如下:

const Start = () => {
    let match = useRouteMatch()
    const [currencies, setCurrencies] = useState([])
    const [currencyPrices, setCurrencyPrices] = useState([])

    useEffect(() => {
        getAllCurrencies()
    }, [])

    const getCurrencyData = async (ticker) => {
        try {
            const response = await KrakenService.getByTicker(ticker)
            return Object.values(response.data.result)[0].c[0]
        } catch (err) {
            console.log(err)
        }
    }

    const getAllCurrencies = async () => {
        try {
            const response = await CryptoCurrencyService.getAll()
            setCurrencies(response.data.results)
        } catch (err) {
            console.log(err)
        }
    }

    return(
        <div className='Start'>
            <Switch>
                <Route path={`${match.path}/:currencyId`}>
                    test
                </Route>
                <Route path={match.path}>

                <Container className="cc-container">
                    <Row>
                        <Table hover className="cc-table">
                        <thead>
                            <tr>
                            <th>#</th>
                            <th>Name</th>
                            <th>Price</th>
                            <th>24h %</th>
                            <th>7d %</th>
                            <th>Market Cap</th>
                            <th>Volume (24h)</th>
                            <th>Circulating Supply</th>
                            <th>Last 30 Days</th>
                            </tr>
                        </thead>

                        {currencies &&
                            currencies.map((item, index) =>
                                <tbody>
                                    <tr>
                                        <td>{index + 1}</td>
                                        <td><Image src={item.logo} width="38" roundedCircle /> {item.name}</td>
                                        <td>{item.pairs}</td> HERE I WANT TO FETCH DATA
                                    </tr>
                                </tbody>
                            )
                        }
                        </Table>
                    </Row>
                </Container>     
                
                </Route>
            </Switch>
        </div>
    )
}

export default Start

Maybe create component for Price information?也许为价格信息创建组件?

// PriceInformation component
const PriceInformation = ({ ticker }) => {
  const [priceInfo, setPriceInfo] = useState(null)
  
  useEffect(() => {
    getCurrencyData(ticker)
  }, [])

  const getCurrencyData = async (ticker) => {
    try {
      const response = await KrakenService.getByTicker(ticker)
      setPriceInfo(Object.values(response.data.result)[0].c[0]);
      // return Object.values(response.data.result)[0].c[0]
    } catch (err) {
      console.log(err)
    }
  }

  return (
    // your code for ui
  )
}
// Start component
const Start = () => {
  // code ...
  return (
    <div className='Start'>
            <Switch>
                <Route path={`${match.path}/:currencyId`}>
                    test
                </Route>
                <Route path={match.path}>

                <Container className="cc-container">
                    <Row>
                        <Table hover className="cc-table">
                        <thead>
                            <tr>
                            <th>#</th>
                            <th>Name</th>
                            <th>Price</th>
                            <th>24h %</th>
                            <th>7d %</th>
                            <th>Market Cap</th>
                            <th>Volume (24h)</th>
                            <th>Circulating Supply</th>
                            <th>Last 30 Days</th>
                            </tr>
                        </thead>

                        {currencies &&
                            currencies.map((item, index) =>
                                <tbody>
                                    <tr>
                                        <td>{index + 1}</td>
                                        <td><Image src={item.logo} width="38" roundedCircle /> {item.name}</td>
                                         
                                        { /* <td>{item.pairs}</td> HERE I WANT TO FETCH DATA */ }
                                        <td><PriceInformation ticker={item.pairs}/></td>
                                    </tr>
                                </tbody>
                            )
                        }
                        </Table>
                    </Row>
                </Container>     
                
                </Route>
            </Switch>
        </div>
   
  )
}

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

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