【发布时间】:2021-12-25 18:52:02
【问题描述】:
这是我第一次在应用程序中使用 React 上下文挂钩,我正在尝试设置 SelectedBackgroundContext,但它不会更新。 console.log(typeof selectBackground) 确实显示为一个函数,所以我相信它正在正确导入,但不确定为什么它没有更新。
我的所有代码都可以在下面的这个 CodeSandbox 链接中找到。我遇到问题的那一行是 child.js:8。
孩子
export default function Child() {
const { selectedBackground } = useContext(SelectedBackgroundContext);
const { selectBackground } = useContext(SelectedBackgroundContext);
selectBackground(null); //Should render text saying "None" instead of image
console.log(selectedBackground);
const renderSelected = (context) => {
if (context) {
return (
<img
style={{ height: "200px" }}
src={context}
key={context + "Thumbnail"}
alt={"thumbnail of " + context}
/>
);
} else {
return <p>None</p>;
}
};
return (
<div>
<p>Background:</p> {renderSelected(selectedBackground)}
</div>
);
}
上下文
export const SelectedBackgroundContext = React.createContext({
selectedBackground:
"https://lp-cms-production.imgix.net/2019-06/81377873%20.jpg?fit=crop&q=40&sharp=10&vib=20&auto=format&ixlib=react-8.6.4",
selectBackground: () => {}
});
如果有任何建议,我将不胜感激!
【问题讨论】:
标签: reactjs react-hooks react-context use-context