我想创建一个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;
}
然而,当我在组件中使用这个"全局状态"时
import { useGlobalState } from '../../context/RoomContextProvider';
....
const [state, setState] = useGlobalState();
我的页面没有呈现,我得到错误信息:
Uncaught TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))
下面是我使用useGlobalState
import { useGlobalState } from '../../context/RoomContextProvider';
...
<useGlobalState>
<SignupForm/>
<useGlobalState/>
您可能还没有将上下文api的调用通过上下文提供程序中的useGlobalState
封装在父组件中,而父组件是访问上下文所必需的。
更新:在您更新的问题中,您将钩子包装为JSX元素,这是不正确的。你必须对提供程序进行包装,然后钩子才能在树中存在于该提供程序下的任何组件中工作。
您可以检查这段修改后的代码,它确实做到了- https://stackblitz.com/edit/react-jfubkz?file=src%2FApp.js
你可以在这里阅读更多关于React Context的用法- https://beta.reactjs.org/apis/usecontext
还有你试图处理
if (value === undefined) throw new Error('Please add RoomContextProvider');
不能工作,因为value在初始化时为null
const RoomContext = createContext(null);