简体   繁体   English

React context throwing TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))

[英]React context throwing TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))

I'm getting the error:我收到错误:

TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))

whenever I try to manage state from useContext .每当我尝试从useContext管理 state 时。 The idea here is to allow for "tokens" to be initialised at [] on page load, then when set in the TokenListBox component, it is subsequently updated in TokenProviderContext .这里的想法是允许在页面加载时在[]处初始化“令牌”,然后在TokenListBox组件中设置时,随后在TokenProviderContext中对其进行更新。

TokenProviderContext.tsx: TokenProviderContext.tsx:

const TokenProviderContext = React.createContext<any>([]);

export const TokenProvider = ({
  children,
}: {
  children:
    | ReactElement<React.ReactNode, string | JSXElementConstructor<unknown>>[]
    | ReactElement<React.ReactNode, string | JSXElementConstructor<unknown>>;
}) => {
  const [selectedTokens, setSelectedTokens] = useState<IToken[]>(sampleTokenList);

  const contextValue = useMemo(
    () => ({
      selectedTokens,
      setSelectedTokens,
    }),
    [selectedTokens, setSelectedTokens],
  );

  return <TokenProviderContext.Provider value={contextValue}>{children}</TokenProviderContext.Provider>;
};

export const useTokenProvider = () => useContext(TokenProviderContext);

TokenListBox.tsx:令牌列表框.tsx:

export default function TokenListBox({ tokenList }: { tokenList: IToken[] }) {
  const [selectedTokens, setSelectedTokens] = useTokenProvider();

  useEffect(() => {
    if (!selectedTokens) {
      setSelectedTokens([]);
    }
  }, [selectedTokens, setSelectedTokens]);

  return (
    <Listbox value={selectedTokens} onChange={setSelectedTokens} multiple>
      {({ open }) => (
        <>
          <div className="relative mt-1">
            <Listbox.Button
              className="relative w-full cursor-default rounded-md border border-gray-300 bg-white
            py-2 pl-3 pr-10 text-left shadow-sm focus:border-sky-500 focus:outline-none focus:ring-1 focus:ring-sky-500
            sm:text-sm"
            >
              <span className="flex items-center">
                <span className="block truncate">Select Tokens</span>
              </span>
              <span className="pointer-events-none absolute inset-y-0 right-0 ml-3 flex items-center pr-2">
                <ChevronUpDownIcon className="h-5 w-5 text-gray-400" aria-hidden="true" />
              </span>
            </Listbox.Button>
            <Transition
              show={open}
              as={Fragment}
              leave="transition ease-in duration-100"
              leaveFrom="opacity-100"
              leaveTo="opacity-0"
            >
              {tokenList.length > 0 && (
                <Listbox.Options
                  className="absolute z-10 mt-1 max-h-56 w-full overflow-auto rounded-md bg-white py-1
              text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm"
                >
                  {tokenList.map((token) => (
                    <Listbox.Option
                      key={token.symbol}
                      className={({ active }) =>
                        classNames(
                          active ? 'text-white bg-sky-600' : 'text-gray-900',
                          'relative cursor-default select-none py-2 pl-3 pr-9',
                        )
                      }
                      value={token.name}
                    >
                      {({ selected, active }) => (
                        <>
                          <div className="flex items-center">
                            <img src={token.iconSrcUrl} alt="" className="h-6 w-6 flex-shrink-0 rounded-full" />
                            <span
                              className={classNames(selected ? 'font-semibold' : 'font-normal', 'ml-3 block truncate')}
                            >
                              {token.name}
                            </span>
                          </div>
                          {selected ? (
                            <span
                              className={classNames(
                                active ? 'text-white' : 'text-sky-600',
                                'absolute inset-y-0 right-0 flex items-center pr-4',
                              )}
                            >
                              <CheckIcon className="h-5 w-5" aria-hidden="true" />
                            </span>
                          ) : null}
                        </>
                      )}
                    </Listbox.Option>
                  ))}
                </Listbox.Options>
              )}
            </Transition>
          </div>
        </>
      )}
    </Listbox>
  );
}

When you call useTokenProvider() you would get as result contextValue , which an object not an array, hence the error you are getting.当您调用useTokenProvider()时,您会得到contextValue的结果,其中 object 不是数组,因此您会遇到错误。

Assuming TokenListBox is wrapped in TokenProvider , this would work:假设TokenListBox包装在TokenProvider中,这将起作用:

const {selectedTokens, setSelectedTokens} = useTokenProvider();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 React Context API 时出错:“TypeError:Object 不可迭代(无法读取属性 Symbol(Symbol.iterator))” - Error while using React Context API: "TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator))" 如何修复:React-Context - TypeError: Object 不可迭代(无法读取属性 Symbol(Symbol.iterator)) - How to fix: React-Context - TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator)) × TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator)) - × TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator)) TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator)) - TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator)) 反应js:TypeError:对象null不可迭代(无法读取属性Symbol(Symbol.iterator)) - react js : TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator)) 未捕获的类型错误:对象在 XMLHttpRequest 中不可迭代(无法读取属性 Symbol(Symbol.iterator))。<anonymous> - Uncaught TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator)) at XMLHttpRequest.<anonymous> TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator)) - 为什么? 这是什么意思? 如何解决? - TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator)) - Why? What does it mean? How to solve it? TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator)) JavaScript - TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator)) JavaScript React - 使用 Hooks 时,出现错误 - Object 不可迭代(无法读取属性 Symbol (Symbol.iterator)) - React - When using Hooks, I get an error - Object is not iterable (cannot read property Symbol (Symbol.iterator)) 获得未定义是不可迭代的(无法读取属性 Symbol(Symbol.iterator)) - getting undefined is not iterable (cannot read property Symbol(Symbol.iterator))
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM