我有新的反应。我正在尝试将数据文件加载到状态数组,而不是直接在状态中放置数据数组。我已经放置了代码。但是这样没有显示数据。
App.js
import React, { Component } from 'react';
import Projects from './Components/Projects';
import data from './data/data'
class App extends Component {
constructor(){
super();
this.state = {
myArrays: [{data}]
}
}
render() {
return (
<div className="App">
<Projects myArrays = {this.state.myArrays} />
</div>
);
}
}
export default App;
如果我替换
,它会起作用<Projects myArrays = {this.state.myArrays} /> with <Projects myArrays = {data} />
这两个有什么区别?为什么不用
加载数据呢? <Projects myArrays = {this.state.myArrays} />
Project.js
import React, { Component } from 'react';
class Projects extends Component {
render() {
let projectItems;
projectItems = this.props.myArrays.map((project,i) =>{
return(
<li key = {i}>{project.title}</li>
);
});
return (
<ul>
{projectItems}
</ul>
);
}
}
export default Projects;
data.js
export default [
{
title: "Obama set for first political event since leaving office",
category: "politics"
},
{
title: 'La Liga refuse to accept PSG payment for Barcelona striker Neymar',
category: "sports"
},
{
title: "Virtu Financial closes KCG's European prop trading business",
category: "business"
}
]
答案 0 :(得分:1)
之间的区别
<Projects myArrays = {this.state.myArrays} />
和
<Projects myArrays = {data} />
是您将数据分配给州的方式
this.state = {
myArrays: [{data}]
}
这将导致this.state.myArrays
看起来像
[{data: [
{
title: "Obama set for first political event since leaving office",
category: "politics"
},
{
title: 'La Liga refuse to accept PSG payment for Barcelona striker Neymar',
category: "sports"
},
{
title: "Virtu Financial closes KCG's European prop trading business",
category: "business"
}
]
}]
将其替换为
this.state = {
myArrays: data
}
您的第一个版本也可以使用