使用上下文API——react



组件1:

import "./styles.css";
import { useState, useEffect, createContext } from "react";
import { Component2 } from "./Component2.js";
export const userContext = createContext();
export default function App() {
const [user, setUser] = useState("vk1");

return (
<div className="App">
<userContext.provider value={{ user, setUser }}>
<Component2 />
</userContext.provider>
</div>
);
}

组件2:

import React from "react";
import { useContext } from "react";
import userContext from "./App";
const Component2 = () => {
const { user, setUser } = useContext(userContext);
setUser("vkk");
return <h1>Hi i am from {user} component2</h1>;
};
export default Component2;

组件3:

import React from "react";
import { useContext } from "react";
import  userContext from "./App";
const Component3 = () => {
const { user, setUser } = useContext(userContext);
setUser("vk");
return <h2>I am from {user} component3</h2>;
};
export default Component3;

期望状态应该在组件之间共享,但得到以下错误。

元素类型无效:期望是字符串(对于内置组件)或类/函数(对于组合组件),但得到:未定义。您可能忘记从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入。

检查App的渲染方法

导入错误

改变→从"/Component2.js"To this =>import Component2 from "/Component2.js">

As well As You gave incorrect words provider As userContext。provider -它是" provider ">

相关内容

  • 没有找到相关文章

最新更新