首页 > 解决方案 > React.useContext 显示为未定义

问题描述

这是我第一次在应用程序中使用 React 上下文挂钩,我的上下文默认值一直显示为“未定义”。

到目前为止的故障排除:

我的所有代码都可以在下面的这个 CodeSandbox 链接中找到:

https://codesandbox.io/s/react-context-troubleshooting-ojnb2?file=/src/child.js

我将不胜感激任何建议!

标签: reactjsreact-hooksreact-contextuse-contextcreatecontext

解决方案


我已将您的代码更改为以下代码及其工作。

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/


推荐阅读