访问上下文状态时出现迭代器错误

Iterator error when accessing context state

我在 React Native 中收到以下代码的错误:

Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array object must have a [symbol.iterator]() method

反-context.js

import React, {useState, createContext} from 'react'

export const CounterContext = createContext();

export const CounterContextProvider = props => {
  const [count, setCount] = useState(0)

  return (
    <CounterContext.Provider value={[count, setCount]}>
      {props.children}
    </CounterContext.Provider>
  );
}

反-display.js

import React, { useContext } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { CounterContext, CounterContextProvider } from '../context/counter-context';

export default function Counter() {
    const [count] = useContext(CounterContext);
    
    return (
        <CounterContextProvider>
            <View style={styles.sectionContainer}>
                <Text style={styles.sectionTitle}>{count}</Text>
            </View>
        </CounterContextProvider>
    )
}

const styles = StyleSheet.create({
    sectionContainer: {
        flex: 1,
        padding: 24,
    }

App.js

<SafeAreaView>
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={styles.scrollView}>
          <View style={styles.body}>
            <Counter/>
          </View>
        </ScrollView>
      </SafeAreaView>

这是什么原因?似乎在反应中工作。

您的 useContext(CounterContext) 调用存在于一个不是 <CounterContextProvider> 的后代的组件中。 <CounterContextProvider> 需要是 <Counter> 的祖先,而不是后代。

至于您收到的错误消息,这是由于赋值语句 const [count] = useContext(CounterContext); 中的数组解构语法对 return 值的 [Symbol.iterator]() 方法进行了隐式调用, 如果存在的话。由于范围内没有提供者并且上下文是在没有传递默认值的情况下创建的,因此您实际上是在评估 const [count] = undefined;