[英]Getting data as variable in react component
I have to get data from another file but as a variable, i'll declare data source in main file.我必须从另一个文件获取数据,但作为一个变量,我将在主文件中声明数据源。 Below is code for component and main file.
下面是组件和主文件的代码。 The problem is in component file because declaring variable like that doesn't working.
问题出在组件文件中,因为这样声明变量不起作用。
Component code:组件代码:
const Sylwetka = ({bg, dataSource}) => {
return (
<div>
<Navbar />
<div className={`h-[50vh] p-4 ${bg}`}>
{{dataSource}.map((data) => {
return (
<div>
<h1 className='text-5xl font-extrabold opacity-60'>{data.title}</h1>
</div>
);
})}
</div>
</div>
)
}
export default Sylwetka
Main app code:主要应用程序代码:
const App = () => {
return (
<div className="lato text-white">
<BrowserRouter>
<Routes>
<Route path='/*' element={<Home />}/>
<Route path='/dahmer' element={<Sylwetka bg='dahmer-bg' dataSource={dahmerData}/>}/>
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
It looks like the issue in your component code is caused by the curly braces around dataSource.看起来您的组件代码中的问题是由数据源周围的大括号引起的。 These curly braces are causing the dataSource variable to be treated as a JavaScript object literal, rather than a variable.
这些大括号导致 dataSource 变量被视为 JavaScript object 文字,而不是变量。
To fix this issue, you can simply remove the curly braces around dataSource:要解决此问题,您只需删除数据源周围的花括号即可:
const Sylwetka = ({bg, dataSource}) => {
return (
<div>
<Navbar />
<div className={`h-[50vh] p-4 ${bg}`}>
{dataSource.map((data) => {
return (
<div>
<h1 className='text-5xl font-extrabold opacity-60'>{data.title}</h1>
</div>
);
})}
</div>
</div>
)
}
export default Sylwetka
With this change, the dataSource variable will be correctly interpreted as a variable, and the map function will be able to iterate over its elements.通过此更改,dataSource 变量将被正确解释为变量,并且 map function 将能够迭代其元素。
You have a syntax error, change " {dataSource}.map " to " dataSource.map ".您有语法错误,将“ {dataSource}.map ”更改为“ dataSource.map ”。
Don't forget to declare your " dahmerData ".不要忘记声明您的“ dahmerData ”。
Give a feedback in comment and put your post to solved if the code below solves your problem.如果下面的代码解决了您的问题,请在评论中提供反馈并解决您的帖子。
Component code:组件代码:
const Sylwetka = ({bg, dataSource}) => { return ( <div> <Navbar /> <div className={`h-[50vh] p-4 ${bg}`}> {dataSource.map((data) => { return ( <div> <h1 className='text-5xl font-extrabold opacity-60'>{data.title}</h1> </div> ); })} </div> </div> ) } export default Sylwetka
Main app code:主要应用程序代码:
const dahmerData = []; // your dataSource variable... const App = () => { return ( <div className="lato text-white"> <BrowserRouter> <Routes> <Route path='/*' element={<Home />}/> <Route path='/dahmer' element={<Sylwetka bg='dahmer-bg' dataSource={dahmerData}/>}/> </Routes> </BrowserRouter> </div> ); } export default App;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.