簡體   English   中英

React,獲取 TypeError:在將全局狀態與 Context 結合使用時,嘗試解構不可迭代的實例無效

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM