reactjs - React.useContext 显示为未定义
问题描述
这是我第一次在应用程序中使用 React 上下文挂钩,我的上下文默认值一直显示为“未定义”。
到目前为止的故障排除:
- 我已经确定 React.createContext 在一个单独的文件中(context.js)
- 我已确保子组件包含在 Provider 中
- 我为 React.createContext() 提供了一个默认值
我的所有代码都可以在下面的这个 CodeSandbox 链接中找到:
https://codesandbox.io/s/react-context-troubleshooting-ojnb2?file=/src/child.js
我将不胜感激任何建议!
解决方案
我已将您的代码更改为以下代码及其工作。
import React, { useContext } from "react";
import { SelectedBackgroundContext } from "./context";
export default function Child() {
const selectedBackground = useContext(SelectedBackgroundContext);
// you can comment out line5 above and uncomment line7 below to verify all other code works
//let 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'
const renderSelected = (context) => {
console.log("Background img src is: " + context); //appears as undefined
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>
);
}
因为您没有从上下文值传递对象,这就是为什么不需要
const {selectedBackground} = useContext(SelectedBackgroundContext);
更多关于解构变量 https://www.javascripttutorial.net/es6/javascript-object-destructuring/
推荐阅读
- javascript - Angular JS 中的动态语言翻译
- algorithm - 2 作为从 0 到 n 的数字中的数字出现的次数,没有得到 O(n) 解决方案?
- python-3.x - 如何在linux中使用python修改文件的最后一行
- python-3.x - boto3 查询列表仅返回最后一个结果
- kubernetes - 有没有办法记录“helm install”加载的所有对象的“kubectl describe”?
- java - 无法在 MainActivity(child) 中查看 BaseActivity(parent) 中创建的 progressBar?
- python - Scrapy保存整个域的每个链接
- python - 为什么我在 discord.py 中出现 TypeError?
- javascript - 无法更改以下 php 应用程序的“计算增值税”逻辑
- java - 有没有一种方法可以在 Java 中从头开始使用 Kafka 流(而不是通过 KafkaConsumer)读取消息?