2017-08-03 47 views
0

我是新来react.And我试图加载数据文件到一个状态数组,而不是直接将数组中的数据状态。下面我已经放置的代码。但这不显示数据。如何在反应中将数据文件加载到状态数组?

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" 
    } 
] 

回答

1

<Projects myArrays = {this.state.myArrays} /> 

之间的区别210
<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 

    } 

和替换它的第一个版本也将工作

+0

谢谢...这是一个愚蠢的错误,我做了 –

+0

考虑接受答案,如果它帮助 –