【问题标题】:Iterator error when accessing context state访问上下文状态时出现迭代器错误
【发布时间】:2020-12-30 15:05:48
【问题描述】:

我在 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>

原因是什么?似乎在反应中起作用。

【问题讨论】:

    标签: javascript react-native react-hooks react-context


    【解决方案1】:

    您的useContext(CounterContext) 调用存在于不是&lt;CounterContextProvider&gt; 后代的组件中。 &lt;CounterContextProvider&gt; 必须是 &lt;Counter&gt; 的祖先,而不是后代。

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

    【讨论】:

      猜你喜欢
      • 2015-02-11
      • 2018-12-08
      • 1970-01-01
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 2016-08-17
      • 2016-09-13
      • 1970-01-01
      相关资源
      最近更新 更多