簡體   English   中英

如何訪問一個功能組件 state 之外的組件? - 反應

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

例如,如果我有從 api 接收數據以填充下拉選擇的功能組件 Dropdown,並使用以下掛鈎更新所選值的 state

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

然后我如何訪問/讀取 Dropdown 組件之外的值(在本例中為數字數組)?

為了更好的上下文,我將首先包括使用 Dropdown 組件的位置:

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;

還有下拉功能組件的完整代碼

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;

我將如何使用/訪問在五個下拉組件中分配給 value 的 arrays?

您的問題“訪問組件外部的值?”的答案? 將會:
您通常無法從該組件外部訪問該功能組件的 state

你可以做的是:

  • 將道具“向下”傳遞(給孩子)
  • props 可以是回調函數,這樣你可以通過 state "up"
  • 使用具有全局 state 的框架,例如redux

現在,最好的解決方案在很大程度上取決於您的用例。

將 state “向上”傳遞的示例是:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM