【发布时间】:2020-06-04 23:39:52
【问题描述】:
我有一个数组,通过 useState 钩子,我尝试通过我通过上下文提供的函数将元素添加到该数组的末尾。然而,数组的长度永远不会超过 2,元素 [0, n] 其中 n 是我在第一个元素之后推送的最后一个元素。
我已经简化了一点,并没有测试过这么简单的代码,不过它并不复杂。
MyContext.tsx
interface IElement = {
title: string;
component: FunctionComponent<any>;
props: any;
}
interface IMyContext = {
history: IElement[];
add: <T>(title: string, component: FunctionComponent<T>, props: T) => void
}
export const MyContext = React.createContext<IMyContext>({} as IMyContext)
export const MyContextProvider = (props) => {
const [elements, setElements] = useState<IElement[]>([]);
const add = <T extends any>(title: string, component: FunctionComponent<T>, props: T) => {
setElements(elements.concat({title, component, props}));
}
return (
<MyContext.Provider values={{elements, add}}>
{props.children}
</MyContext.Provider>
);
}
在其他元素中,我使用此上下文添加元素并显示当前元素列表,但无论添加多少,我都只会得到 2 个。
我通过 onClick 从各种元素中添加,并通过使用添加的组件的侧边栏显示。
SomeElement.tsx
const SomeElement = () => {
const { add } = useContext(MyContext);
return (
<Button onClick=(() => {add('test', MyDisplay, {id: 42})})>Add</Button>
);
};
DisplayAll.tsx
const DisplayAll = () => {
const { elements } = useContext(MyContext);
return (
<>
{elements.map((element) => React.createElement(element.component, element.props))}
</>
);
};
【问题讨论】:
-
你在哪里只看到这两个元素?是通过
history吗?history设置为什么? -
Array.concat 连接两个数组,你正在连接一个对象。应该是
elements.concat([{title, component, props}]) -
不真实,@Ibraheem。要连接的项目可以直接传入;您不必传入数组。观察
[].concat('woo') -> ['woo'] -
@Jacob 谢谢你!
-
history是否应该与elements相同,或者两者之间是否存在某些层?我很困惑,因为您传递的是<MyContext.Provider values={{history, add}}>(也应该只是value)。只是想确保您正确地实例化您的提供程序。
标签: javascript reactjs react-hooks react-context