【发布时间】: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