简体   繁体   中英

How can I access a functional components state outside the component? - React

For example, if I have the functional component Dropdown that receives data from an api to populate a dropdown selection, and uses the following hook to update the state of the value selected

const [value, setValue] = React.useState();

How might I then access/read the value (in this case an array of numbers) outside of the Dropdown component?

For better context I will include firstly where the Dropdown component is used:

import React from 'react';
import Dropdown from '../Components/Dropdown.js'
import GraphTypeDropdown from '../Components/GraphTypeDropdown.js'

function CreateGraph() {

    //function receiving and returning data (array of data points and their heading) from api

    async function getData() {
        const response = await fetch('/dropdowndata');
        const receivedData = await response.json();
        return receivedData;
    }

    //assigning data to myData variable

    const myData = getData();

    //myData is passed to Dropdown components as a prop to allow selection of data columns
    //GraphTypeDropdown allows selection of the graph "type"

    return (
        <div>
            <Dropdown myData={myData} />
            <Dropdown myData={myData} />
            <Dropdown myData={myData} />
            <Dropdown myData={myData} />
            <Dropdown myData={myData} />
            <GraphTypeDropdown />
        </div>
    )
}

export default CreateGraph;

And also the full code of the dropdown functional component

import React from 'react';
import './Dropdown.css';

function Dropdown(props) {
    const [columns, setColumns] = React.useState([]);
    const [value, setValue] = React.useState();

    //maps the prop myData to be the label and value of the dropdown list

    React.useEffect(() => {
        async function getColumns() {
            props.myData.then(function(result) {
                setColumns(result.map(({ heading, values }) => ({ label: heading, value: values })));
            });
        }
        getColumns();
    }, [props.myData]);

    //creates a dropdown where value (array of data points) can be selected with label (column headings)
    //value selected is then saved in the state of the dropdown

    return (
        <select className='DropDown'
            value={value}
            onChange={(e) => setValue(e.currentTarget.value)}
        >
            {columns.map(({ label, heading, value }) => (
                <option className='DropDown'
                    key={heading}
                    value={value}
                >
                    {label}
                 </option>
            ))}
        </select>
    );
}

export default Dropdown;

How will I be able to use/access the arrays assigned to value in the five Dropdown components?

The answer to your question "access the value outside of the component?" would be:
You generally can not access the state of a functional component from outside that component .

What you can do is:

  • pass props "down" (to children)
  • props can be callback functions, this way you could pass state "up"
  • use a framework with global state, like redux .

Now it depends a lot on your use case what the best solution is.

An example for passing the state "up" would be:

function Dropdown(props) {
    // ...
    React.useEffect(() => {
        props.onLoaded( columns );
    }, [ columns ]);
    // ...
}

function CreateGraph() {
    // ...
    <Dropdown
        myData={ myData }
        onLoaded={
            (columns) => {
                console.log('columns:', columns);
            }
        }
    />
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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