我有一个上下文,是提供给我的整个应用程序。在上下文中,是一种数组状态,它保存键以过滤应用程序上显示的数据。我使用的是这下拉选择器,它是一个接受JSON数据并显示它的树选择器。它有一个如何防止父呈现时重新呈现的示例,但我无法使它对功能组件起作用。
当在下拉列表中进行选择时,它会将当前选定的所有内容传递给onchange处理程序,并在处理程序中将上下文中的状态数组设置为下拉列表传递的数组。状态更改会导致下拉组件使用App传递的初始数据重新呈现,将其作为一个支柱,重置为不检查任何内容。
我已经考虑过使用React.memo来尝试防止下拉列表重新呈现,但是无法让它工作。防止下拉列表的重新呈现是解决此问题的方案A。
全局上下文代码
import React, {useState} from 'react';
//Typing for global state
type globalStateObj = {
Fleets: string[];
updateFleets: (value: string[])=>void;
}
//Context creation with initial
export const stateContext = React.createContext<globalStateObj>({
Fleets: [""],
updateFleets: ()=>{}
})
export const GlobalStateProvider = (props: {children: any}) =>{
const [fleets, setFleets] = useState([""]);//states should match stateContext
//Handlers for updating state
const updateFleetHandler = (value: string[])=>{
setFleets(value);
}
//Setting values to state and handlers
const conextValue: globalStateObj = {
Fleets: fleets,
updateFleets: updateFleetHandler,
}
return(
<stateContext.Provider value={conextValue}>
{props.children}
</stateContext.Provider>
)
}; 下拉组件代码
import { stateContext } from "../GlobalState";
import './DropdownFilterBar.scss';
import "react-dropdown-tree-select/dist/styles.css";
interface DropdownFilterBar_Props{
data: any[]
}
export const DropdownFilterBar = (props: DropdownFilterBar_Props) =>{
const globalState = useContext(stateContext);
const handleChange = (selected: any, allchecked: TreeNode[]) =>{
let results = allchecked.map(({value})=>value);
console.log(results);
globalState.updateFleets(results);
}
const texts: TextProps = {
placeholder:"Fleets",
inlineSearchPlaceholder:"Search"
}
return(
<div className="DropDownFilterBar">
<DropdownTreeSelect
data={props.data}
onChange={(selected, allchecked) =>{handleChange(selected, allchecked)}}
className="fleet-selector"
inlineSearchInput={true}
texts={texts}
/>
</div>
)
};App.tsx ContextProvider所处的
<div className="App">
<Container className="themed-container">
<Row className='navRow'>
<Col><TopNavBar/></Col>
</Row>
<GlobalStateProvider>
<Row className="DropdownFilterRow">
<Col><DropdownFilterBar data={DropdownFilterData}/></Col>
</Row>
<Row>
<Col className="dashboard">
<Routes>
<Route path="/overview" element={<Home/>} />
...发布于 2022-03-14 19:32:11
我最后使用的解决方案是useMemo挂钩,而不是React.Memo。useContext使用React.Memo强制进行重呈现。我意识到可以使用useMemo来记忆带有对props.data的依赖关系的JSX元素。下拉组件代码现在如下所示
const dropdown = useMemo(()=>{
return(
<DropdownTreeSelect
data={props.data}
onChange={(selected, allchecked) =>{handleChange(selected, allchecked)}}
className="fleet-selector"
inlineSearchInput={true}
texts={texts}
/>
)}, [props.data]);
return(
<div className="DropDownFilterBar">
{dropdown}
</div>
)https://stackoverflow.com/questions/71441319
复制相似问题