简体   繁体   English

React - 如何将 API 数据从一个组件传递到另一个 js 文件中的另一个组件?

[英]React - How can I pass API data from one component to another in a different js file?

Lets say I want to pass the data from the getData axios request in my code below to another function located in a different file in my react app.假设我想将下面代码中的getData axios 请求中的数据传递给位于我的 react 应用程序中不同文件中的另一个 function。

export default function Bucket() {

    const { slug } = useParams();
    const classes = useStyles();

    const [data, setData] = useState({ bucket: [] });

    useEffect(() => {
        axiosInstance.get('bucket/' + slug + '/').then((res) => {
            setData({ bucket: res.data });
            console.log(res.data);
        });
    }, [setData, slug]);

    const getData = () => {
        axiosInstance
        .get('bucket/fin-data/' + slug).then((response) => {
                console.log(response)
            })
    }

    return (
        <Container component="main" maxWidth="md">
            <CssBaseline />
            <div className={classes.paper}></div>
            <div className={classes.heroContent}>
                <Container maxWidth="sm">
                    <Typography
                        component="h1"
                        variant="h2"
                        align="center"
                        color="textPrimary"
                        gutterBottom
                    >
                        {data.bucket.name}
                    </Typography>
                    <Typography
                        variant="h5"
                        align="center"
                        color="textSecondary"
                        paragraph
                    >
                        {data.bucket.about}
                    </Typography>
                    <SymbolInput/>
                </Container>
                <button onClick={getData}>get data</button> 
            </div>
        </Container>
    );
}

Instead of calling my API twice, how would I go about passing that data to another component?而不是调用我的 API 两次,我将如何 go 将该数据传递给另一个组件? Most of the examples I'm looking at use classes, I would like to use functions instead.我正在查看的大多数示例都使用类,我想改用函数。

For example, how can I pass that data to this chart, specifically where I marked.例如,我如何将该数据传递到此图表,特别是我标记的位置。 Pseudocode is welcomed, also please change around the example chart if needed:欢迎使用伪代码,如果需要,也请更改示例图表:

const BarChart = () => {
  return (
    <div>
      <Pie
        data={{
          labels:<HERE>,
          datasets: [
            {
              label: '# of votes',
              data: <HERE>,
              backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)',
              ],
              borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)',
              ],
              borderWidth: 1,
            },
          ],
        }}
        height={400}
        width={600}
        options={{
          maintainAspectRatio: false,
          scales: {
            yAxes: [
              {
                ticks: {
                  beginAtZero: true,
                },
              },
            ],
          },
          legend: {
            labels: {
              fontSize: 25,
            },
          },
        }}
      />
    </div>

In React, You can pass the data two way most commonly:在 React 中,您可以通过两种最常见的方式传递数据:

1. 1.

  • Pass a callback function to from common main to child component.将回调 function 从公共主组件传递到子组件。
  • When async action is done, execute it with data.完成异步操作后,使用数据执行它。
  • Give it the data with props to another component.将带有道具的数据提供给另一个组件。
export default function Bucket({ onGetData }) {

    const { slug } = useParams();
    const classes = useStyles();

    const [data, setData] = useState({ bucket: [] });

    useEffect(() => {
        axiosInstance.get('bucket/' + slug + '/').then((res) => {
            setData({ bucket: res.data });
            console.log(res.data);
        });
    }, [setData, slug]);

    const getData = () => {
        axiosInstance
        .get('bucket/fin-data/' + slug).then((response) => {
                onGetData(response);
                console.log(response)
            })
    }

    return (
        <Container component="main" maxWidth="md">
            <CssBaseline />
            <div className={classes.paper}></div>
            <div className={classes.heroContent}>
                {...}
                <button onClick={getData}>get data</button> 
            </div>
        </Container>
    );
}
export default function MainComponent() {

    const [data, setData] = useState({});
      
    const onGetData = (result) => {
        setData(result);
    };

    return (
        <MainComponent>
          <Bucket onGetData={onGetData} />
          <BarChart data={data} /> 
        </MainComponent>
    );
}
  1. You can pass with any state Manager: Redux, Mobx eg您可以通过任何 state 经理:Redux,Mobx 例如

暂无
暂无

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

相关问题 React js:我可以将数据从一个组件传递到另一个组件吗? - React js: can I pass data from a component to another component? 在 React/Next.js 中,如何简单地将数据从一个页面的组件传递到另一个页面上的组件? - How can I simply pass data from a component one page to a component on another page in React/Next.js? 如何在 React.JS 中将数据从一个组件传递到另一个组件 - How to pass data from one component to another in React.JS React:如何从一个组件获取API数据并将其传递给另一组件 - React: How to get API data from one component and pass it to another 如何在 React.js 中将状态/数据从一个组件传递到另一个组件(特别是 riot api) - How to pass state/data from one component to another in React.js (riot api specifically) React / Redux:如何将此状态从一个组件传递到另一个文件? - React/Redux: How can I pass this state from one component to another file? 如何使用 React 将数据从列表传递到另一个组件? - How can I pass a data to another component from a list with React? 如何使用React js在onchange中将数据从一个组件传递到另一个组件 - How to pass data from one component to another component in onchange using React js 如何将数据从一个页面传递到另一个 React JS - How can I pass data from one page to another React JS 如何将数据从 React 组件传递到主文件? - How can I pass data from a React component to main file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM