如何解决访问上下文状态时出现迭代器错误
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>
是什么原因?似乎可以做出反应。
解决方法
您的watchlist = watchlist.dropna()
调用存在于不是useContext(CounterContext)
的后代的组件中。 <CounterContextProvider>
必须是<CounterContextProvider>
的祖先,而不是后代。
对于您收到的错误消息,这是由于赋值语句<Counter>
中的数组分解语法引起的,该语句隐式调用返回值的const [count] = useContext(CounterContext);
方法(如果存在)。由于作用域中没有提供程序,并且上下文是在未传递默认值的情况下创建的,因此您实际上是在评估[Symbol.iterator]()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。