简体   繁体   中英

Iterator error when accessing context state

I get this error for the following code in React Native:

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

counter-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>
  );
}

counter-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>

What is the reason? Seems to work in react.

Your useContext(CounterContext) call exists in a component that is not a descendant of <CounterContextProvider> . The <CounterContextProvider> needs to be an ancestor of <Counter> , not a descendant.

As for the error message you're getting, it's due to the array destructuring syntax in the assignment statement const [count] = useContext(CounterContext); which makes an implicit call to the return value's [Symbol.iterator]() method, if it exists. Since there is no provider in scope and the context was created without passing a default value, you're essentially evaluating const [count] = undefined;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM