如何解决如何访问组件外部的功能组件状态? - 反应
例如,如果我有一个功能组件 Dropdown 从一个 api 接收数据来填充一个下拉选择,并使用以下钩子来更新所选值的状态
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;
我将如何使用/访问在五个 Dropdown 组件中分配给 value 的数组?
解决方法
您的问题“访问组件外部的值?”的答案是:
您通常无法从组件外部访问功能组件的状态。
你可以做的是:
- “向下”传递道具(给孩子们)
- props 可以是回调函数,这样你就可以传递状态“up”
- 使用具有全局状态的框架,例如 redux。
现在,最佳解决方案在很大程度上取决于您的用例。
传递“向上”状态的示例是:
function Dropdown(props) {
// ...
React.useEffect(() => {
props.onLoaded( columns );
},[ columns ]);
// ...
}
function CreateGraph() {
// ...
<Dropdown
myData={ myData }
onLoaded={
(columns) => {
console.log('columns:',columns);
}
}
/>
// ...
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。