![](/img/trans.png)
[英]TypeError: Invalid attempt to destructure non-iterable instance React/Jest
[英]React, Getting TypeError: Invalid attempt to destructure non-iterable instance when using global state with Context
我嘗試使用上下文來全局訪問狀態,但出現以下錯誤:
TypeError: Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.
我試圖通過從這個Stack Overflow Question調整上下文的使用來解決這個問題。
我想從中獲取狀態的文件:
const test = () => {
const [selectedValueRound, setSelectedValueRound] = useState("10 rounds");
return (
<View>
<RoundContext.Provider
value={[selectedValueRound, setSelectedValueRound]}
>
<View>
<Picker
selectedValue={selectedValueRound}
onValueChange={(itemValue, itemIndex) =>
setSelectedValueRound(itemValue)
}
>
<Picker.Item label="1 round" value="0"></Picker.Item>
<Picker.Item label="2 rounds" value="1"></Picker.Item>
</Picker>
</View>
</RoundContext.Provider>
</View>
);
};
上下文文件:
export const RoundContext = createContext(false);
我嘗試調用上下文並出現錯誤的文件:
const SomeFile = () => {
const [selectedValueRound, setSelectedValueRound] = useContext(RoundContext);
return (
<View>
<Text>{selectedValueRound}</Text>
</View>
);
};
export default SomeFile;
為了使它起作用,請確保將SomeFile
包裝在RoundContext.Provider
中,因為現在看來您沒有這樣做。
只有提供者內部的包裝組件才能使用上下文。
另外,確保每個 React 組件都以大寫字母開頭, Test
而不是test
const Test = () => {
const [selectedValueRound, setSelectedValueRound] = useState("10 rounds");
return (
<View>
<RoundContext.Provider
value={[selectedValueRound, setSelectedValueRound]}
>
<View>
<Picker
selectedValue={selectedValueRound}
onValueChange={(itemValue, itemIndex) =>
setSelectedValueRound(itemValue)
}
>
<Picker.Item label="1 round" value="0"></Picker.Item>
<Picker.Item label="2 rounds" value="1"></Picker.Item>
</Picker>
</View>
<SomeFile/>
</RoundContext.Provider>
</View>
);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.