如何从另一个组件范围内的组件中的 useState 声明变量中检索内容

How can I retrieve stuff from an useState declared variable in a component within another component scope

我想获取另一个组件范围内的 investments 变量...

下面的代码我已经写好了,但是我已经导出了函数 InvestmentsList,我怎么才能得到这个 const investment?如果不求助于 react-redux 的 useSelector() 如何做到这一点?

import React, { useEffect, useState } from 'react';
import {
  Card,CardBody,CardHeader,CardTitle,Col,Row,Table} from 'reactstrap';
import moment from 'moment';

const InvestmentsList = () => {
  const [investment, setInvestment] = useState([]);
 async function fetchInvestments() {
    const response = await fetch('http://localhost:3000/products');
    const investments = await response.json();
    // waits until the request completes...
    setInvestment(investments);
  }

  useEffect(() => {
    fetchInvestments();
  }, []);

  return (
    <>{/* ...Returns something */}</>)
export default InvestmentsList;

您无法访问其他组件的数据。

如果两个组件相距不远,你也可以将数据存储在一个父组件中,并为两个组件提供“投资”作为道具。

此外,Redux、React Context API 或 RecoilJS 将允许您将变量“investment”的数据存储在组件外部的某个地方。