【问题标题】:How can I access a functional components state outside the component? - React如何访问组件外部的功能组件状态? - 反应
【发布时间】:2021-01-11 15:18:21
【问题描述】:

例如,如果我有从 api 接收数据以填充下拉选择的功能组件 Dropdown,并使用以下钩子更新所选值的状态

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 的数组?

【问题讨论】:

  • 对于您的具体情况(&lt;Dropdown /&gt;-components 是 &lt;CreateGraph /&gt;-component 的直接子级,应该使用数据),我建议利用 Lift Stat Up 技术
  • 而且,顺便说一下,如果您希望获得与现有代码库相关的可行代码形式的建议,我建议您设置实时沙箱(例如在 stackblitz.com 或codeandbox.io)
  • 您需要在CreateGraph 上启动下拉菜单的状态,并将valuesetValue 函数作为道具传递给它们。您可以执行 5 个 useState 函数或使用一个对象/数组并将每个函数绑定到一个键或索引。
  • 实现和两个组件的连接方式似乎有很多问题。

标签: javascript reactjs react-hooks react-state


【解决方案1】:

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

你可以做的是:

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

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

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

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

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

【讨论】:

  • 感谢您的宝贵时间和有用的评论,因为您可能会告诉我,我是 React/Javascript 和一般编码的新手,所以这个答案使事情尽可能清楚。我将更多地研究提升状态,看看我是否能够以这种方式实现这一点以实现我的结果。
猜你喜欢
  • 2022-11-21
  • 1970-01-01
  • 2019-05-22
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 2021-05-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多