2017-08-03 67 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

考慮接受答案,如果它幫助 –

相關問題