英文:
I don't know why I am getting error while exporting FirstName?
问题
import React, { createContext } from 'react';
import './App.css';
import ComA from './ComA.jsx';
function App() {
const FirstName = createContext();
return (
<>
<FirstName.Provider value={'Ganesh'}>
<ComA />
</FirstName.Provider>
</>
);
}
export default App;
export { FirstName };
英文:
import React, { createContext } from 'react';
import './App.css';
import ComA from './ComA.jsx';
function App() {
const FirstName = createContext();
return (
<>
<FirstName.Provider value={'Ganesh'}>
<ComA />
</FirstName.Provider>
</>
);
}
export default App;
export { FirstName };
output:
ERROR in \[eslint\]
src\\App.js
Line 28:9: Parsing error: Export 'FirstName' is not defined. (28:9)
webpack compiled with 2 errors
答案1
得分: 1
以下是代码部分的中文翻译:
错误信息表明,您正在尝试导出尚未定义的内容。在这种情况下,您正尝试导出FirstName上下文,但它仅在App组件中已定义。
要修复此错误,您可以将createContext移出App组件并直接导出它。以下是一个示例:
import React, { createContext } from 'react';
import './App.css';
import ComA from './ComA.jsx';
export const FirstNameContext = createContext();
function App() {
return (
<FirstNameContext.Provider value={'Ganesh'}>
<ComA />
</FirstNameContext.Provider>
);
}
export default App;
通过这个更改,您现在可以在其他文件中导入FirstNameContext:
import React, { useContext } from 'react';
import { FirstNameContext } from './App';
function ComA() {
const firstName = useContext(FirstNameContext);
return (
<div>
我的名字是 {firstName}。
</div>
);
}
export default ComA;
英文:
The error message suggests that you are trying to export something that has not been defined. In this case, you are trying to export the FirstName context, but it has only been defined within the App component.
To fix this error, you can move the createContext outside of the App component and export it directly. Here is an example:
import React, { createContext } from 'react';
import './App.css';
import ComA from './ComA.jsx';
export const FirstNameContext = createContext();
function App() {
return (
<FirstNameContext.Provider value={'Ganesh'}>
<ComA />
</FirstNameContext.Provider>
);
}
export default App;
With this change, you can now import the FirstNameContext in other files:
import React, { useContext } from 'react';
import { FirstNameContext } from './App';
function ComA() {
const firstName = useContext(FirstNameContext);
return (
<div>
My name is {firstName}.
</div>
);
}
export default ComA;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论