Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
73 views
in Technique[技术] by (71.8m points)

javascript - 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.

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? 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>
question from:https://stackoverflow.com/questions/65851197/react-how-can-i-pass-api-data-from-one-component-to-another-in-a-different-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In React, You can pass the data two way most commonly:

1.

  • Pass a callback function to from common main to child component.
  • 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 e.g.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...