【问题标题】:context is giving me undefined上下文给了我未定义的
【发布时间】:2021-09-22 18:47:18
【问题描述】:

我不确定为什么在初始加载后上下文中的值变得未定义。

我写上下文的方式是:

export const ProductListContext = createContext({});

export const useListProductContext = () => useContext(ProductListContext);

export const ListProductContextProvider = ({ children }) => {
  const [listProduct, setListProduct] = useState({
    images: [],
    title: "Hello",
  });
  return (
    <ProductListContext.Provider value={{ listProduct, setListProduct }}>
      {children}
    </ProductListContext.Provider>
  );
}; 

关于我的组件的初始加载。我让 listProduct 正确,因为 console.log 会产生

the list is Object {
  "images": Array [],
  "title": "Hello",
}

问题是当我尝试再次读取listProduct 后,它说它是未定义的,除非我将它保存到useState。对此的任何帮助表示赞赏。问题出在pickImage 函数内

// Initial has all properties correctly
const { listProduct, setListProduct } = useListProductContext();
// Seems to work at all times when I save it here
const [product] = useState(listProduct);
console.log('the list product listed is ', listProduct);
useEffect(() => {
  (async () => {
    if (Platform.OS !== 'web') {
      const {
        status,
      } = await ImagePicker.requestMediaLibraryPermissionsAsync();
      if (status !== 'granted') {
        alert('Sorry, we need camera roll permissions to make this work!');
      }
    }
  })();
}, []);

const pickImage = async () => {
  let result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: ImagePicker.MediaTypeOptions.Images,
    allowsEditing: true,
    aspect: [4, 3],
    quality: 1,
    exif: true,
  });
  // PROBLEM - listProduct is undefined
  console.log('before copy it is ', listProduct);
  const listProduct = { ...product };
  console.log('the list is', listProduct);
  listProduct.images.push(result.uri);
  // listProduct.images.push(result.uri);
  // const images = listProduct.images;
  // images.push(result.uri);
  setListProduct({ ...listProduct });
  return;
};

【问题讨论】:

  • 你的 useListProductContext 可能违反了钩子的规则,因为 React 看到 use 限定符来验证钩子的规则。 reactjs.org/docs/hooks-custom.html
  • @TR3 决定移除世界“使用”并使其正常工作。我不知道这个规则,因为在另一个项目中使用用户令牌没有产生任何问题。我把它作为useUser。如果可能,请回复为答案,以便我接受。谢谢
  • 乐于助人,容易错过的“陷阱”

标签: reactjs react-native react-context


【解决方案1】:

你的 useListProductContext 违反了钩子规则,因为 React 看到 use 限定符来验证钩子规则。

Rules of Hooks

Using a Custom Hook

“我是否必须以“use”开头来命名我的自定义 Hook?请这样做。这个约定非常重要。没有它,我们将无法自动检查违反 Hooks 规则,因为我们无法判断某个函数是否包含对 Hooks 内部的调用。”

【讨论】:

  • 链接中哪里说变量不能以use为前缀?这应该包含在您的答案中
  • 已修复...很好
  • 有机会他可以使用const useListProductContext =&gt; useContext(ProductListContext); 并且很好
猜你喜欢
  • 2023-03-03
  • 1970-01-01
  • 2019-09-19
  • 1970-01-01
  • 1970-01-01
  • 2018-09-26
  • 1970-01-01
  • 2018-05-30
  • 1970-01-01
相关资源
最近更新 更多