繁体   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