2017-07-27 41 views
1

您好我正在從api中提取數據,我想採取數據並將其呈現給dom,但我錯誤「Uncaught TypeError:無法讀取屬性'map'未定義在Topicselect.render」提取數據,然後將其渲染到dom React

這裏基本上是我在做什麼,雖然我已經抽象化了什麼,是不是這個問題直接相關的,如實際主題名稱,進口等:

class Topics extends Component{ 
    constructor(props){ 
    super(props); 
    this.state = { 
     topics: [] 
    } 
    } 
    componentWillMount(){ 
     fetch('/api').then((res)=>r.json().then((data)=>{ 
       // push topics into this.state.topics somehow 
     }) 
     console.log(this.state.topics) //returns ['topic1','topic2','topic3']; 
    } 
    render(){ 
    const list = this.state.topics.map((topic)=>{ 
     return(<li>{topic}</li>); 
    }) 
    return(
     <ul> 
     {list} 
     </ul> 
    ) 
    } 
} 

誰能告訴我如何解決這個問題?我看到這裏的答案是說要用componentDidMount代替componentWillMount但不是爲我工作

+0

您發佈的錯誤似乎不符合您的代碼。你有上課「Topicselect」嗎? – Philipp

回答

0

你後取缺少一個右括號)而且它確實推薦使用componentDidMount()而不是componentWillMount()從獲取數據一個API。

在從API接收到數據以確保組件重新渲染後,也不要忘記使用this.setState({ topics: data.howeverYourDataIsStructured });

class Topics extends Component{ 
    constructor(props){ 
    super(props); 
    this.state = { 
     topics: [] 
    } 
    } 

    componentDidMount() { 
    fetch('/api').then((res)=>r.json().then((data)=>{ 
     this.setState({ topics: data.topics }); 
    })); 
    console.log(this.state.topics) //returns []; 
    } 

    render() { 
    console.log(this.state.topics) //returns [] the first render, returns ['topic1','topic2','topic3'] on the second render; 
    return(
     <ul> 
     {this.state.topics.map(topic => (
      <li>{topic}</li> 
     ))} 
     </ul> 
    ) 
    } 
} 
1

確保您使用setState()更新您的狀態,否則render()不會被觸發更新DOM。還要確保你不只是覆蓋當前的狀態,而是將新的主題添加到舊的主題。 (不適合此情況下,但仍必須提到)

一種方式做到這一點是:

componentDidMount() { 
    var currentTopics = this.state.topics; 
    fetch('/api').then((res) => r.json().then((data) => { 
      currentTopics.push(data); 
     })); 
    this.setState({'topics': currentTopics}); 
} 

但你也可以撥打setState()內循環。 setState() does not work synchronously因此,如果在實際執行更改之前還有其他更改需要等待,然後觸發render

componentDidMount() { 
    fetch('/api').then((res) => r.json().then((data) => { 
     this.setState((state) => ({ topics: [...state.topics, data]})); 
    })); 
}