简体   繁体   English

尝试在组件中导入和使用全局状态时,对象 null 不可迭代

[英]Object null is not iterable when trying to import and use global state in component

I would like to create a globalState to track a few properties I would like to pass down to multiple components.我想创建一个 globalState 来跟踪我想传递给多个组件的一些属性。

const initialState = {
    nickname: '',
    selectedRoom: null,
    rooms: [],
    createdRoomTopic: '',
    twilioToken: '',
    device: null
};

const RoomContext = createContext(null);

export const RoomContextProvider = ({ children }) => {
    const[state, setState] = useState(initialState);
    return (
        <RoomContext.Provider value={[state, setState]}>{children}</RoomContext.Provider>
    )
};

export const useGlobalState = () => {
    const value = useContext(RoomContext)
    if(value === undefined) throw new Error('Please add RoomContextProvider');
    return value;
}

However when I use this 'global state' in a component但是,当我在组件中使用此“全局状态”时

import { useGlobalState } from '../../context/RoomContextProvider';
....
const [state, setState] = useGlobalState();

My page does not render and I get the error message:我的页面没有呈现,我收到错误消息:

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

UPDATE Here's an example of where I used useGlobalState更新这是我使用useGlobalState的示例

import { useGlobalState } from '../../context/RoomContextProvider';
...
<useGlobalState>
    <SignupForm/>
<useGlobalState/>

You have probably not wrapped the invocation of the context api via useGlobalState inside the context provider in a parent component, which it needs to be in order to access the context.您可能没有通过useGlobalState在父组件的上下文提供程序中包装上下文 api 的调用,它需要它才能访问上下文。

Update: in your updated question you are wrapping the hook as JSX element, which is incorrect.更新:在您更新的问题中,您将钩子包装为 JSX 元素,这是不正确的。 You have to do the wrapping with the provider and then the hook will work in any component that exists under the provider in the tree.您必须使用提供程序进行包装,然后挂钩将在树中提供程序下存在的任何组件中工作。

You can check this modified code that does the exactly that - https://stackblitz.com/edit/react-jfubkz?file=src%2FApp.js您可以检查这个修改后的代码,它完全可以做到这一点 - https://stackblitz.com/edit/react-jfubkz?file=src%2FApp.js

You can read more about usage of React Context here - https://beta.reactjs.org/apis/usecontext您可以在此处阅读有关 React Context 使用的更多信息 - https://beta.reactjs.org/apis/usecontext

Also your attempt to handle还有你试图处理

if (value === undefined) throw new Error('Please add RoomContextProvider');

does not work because value is null initaly as per initialization as below不起作用,因为根据初始化,初始值为 null,如下所示

const RoomContext = createContext(null);

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

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