Javascript 访问上下文状态时出现迭代器错误
在React Native中,以下代码出现此错误:Javascript 访问上下文状态时出现迭代器错误,javascript,react-native,react-hooks,react-context,Javascript,React Native,React Hooks,React Context,在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 Co
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>
);
}
import React,{useState,createContext}来自“React”
export const CounterContext=createContext();
export const CounterContextProvider=props=>{
const[count,setCount]=useState(0)
返回(
{props.children}
);
}
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,
}
import React,{useContext}来自“React”;
从“react native”导入{View,Text,StyleSheet};
从“../context/counter-context”导入{CounterContext,CounterContextProvider};
导出默认函数计数器(){
const[count]=useContext(CounterContext);
返回(
{count}
)
}
const styles=StyleSheet.create({
节容器:{
弹性:1,
填充:24,
}
App.js
<SafeAreaView>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={styles.scrollView}>
<View style={styles.body}>
<Counter/>
</View>
</ScrollView>
</SafeAreaView>
原因是什么?似乎在react中起作用。您的useContext(CounterContext)
调用存在于不是
后代的组件中。
必须是
的祖先,而不是后代
至于您得到的错误消息,这是由于赋值语句const[count]=useContext(CounterContext);
中的数组解构语法导致的,它隐式调用了返回值的[Symbol.iterator]()
method,如果它存在的话。由于作用域中没有提供程序,并且上下文是在没有传递默认值的情况下创建的,因此您实际上是在计算const[count]=undefined;