javascript - 如何访问组件外部的功能组件状态? - react

标签 javascript reactjs react-hooks react-state

例如,如果我有一个功能组件 Dropdown,它从 api 接收数据来填充下拉选项,并使用以下钩子(Hook)来更新所选值的状态

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

然后我如何访问/读取下拉组件外部的值(在本例中为数字数组)?

为了更好的上下文,我将首先包括使用下拉组件的位置:

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;

我如何能够使用/访问分配给五个下拉组件中的值的数组?

最佳答案

您的问题“访问组件外部的值?”的答案是:
您通常无法从功能组件外部访问该组件的状态

你能做的是:

  • 将 Prop “向下”传递给 child
  • props 可以是回调函数,这样你就可以传递状态“up”
  • 使用具有全局状态的框架,例如 redux .

现在,最佳解决方案是什么在很大程度上取决于您的用例。

“向上”传递状态的示例是:

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

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

关于javascript - 如何访问组件外部的功能组件状态? - react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65669542/

相关文章:

reactjs - 带有 hooks 的 React 组件作为 npm 模块

reactjs - 在使用带有钩子(Hook)的导出类时,我应该远离类吗?

reactjs - RTK 查询 - 表单提交突变后调度操作

javascript - 复制 "/"之后的 URL 并粘贴到按钮上

javascript - 正则表达式,选择字符的任意组合且区分大小写

javascript - 仅在功能 1 和 2 完成后才调用功能 3

reactjs - 如何在 react-bootstrap 自定义上自定义选项卡

javascript - jQuery 无法在 Firefox 中加载

reactjs - 是的/使用 Formik 文件上传验证

reactjs - enzyme `mount` 不呈现 `Route` 元素