2017-10-04 77 views
0

爲什麼這段代碼不起作用? 我只想爲道具設置這個類的狀態,但狀態一直是空的。我無法爲道具設置狀態值

class BillsList extends React.Component{ 
 
    constructor (props: any){ 
 
      super(props); 
 
      this.state = {currentList : this.props.list}; 
 
    }; 
 
    render(){ 
 
     console.log(this.props.list); //It worked..! 
 
     console.log(this.state.currentList); //But this is empty 
 
     return(
 
      <div className="bill_list"> 
 
       {this.state.currentList.map((item,i)=> 
 
        <BillsItem key ={i} value={item} /> 
 
       )} 
 
      </div> 
 
     ) 
 
    } 
 
};

'名單' 是這樣的 enter image description here

回答

0

數組對象,您應該修改如下代碼:

class BillsList extends React.Component{ 
    constructor (props){ 
      super(props); 
      this.state = {currentList : props.list}; 
    }; 
    render(){ 
     console.log(this.props.list); //It worked..! 
     console.log(this.state.currentList); //But this is empty 
     return(
      <div className="bill_list"> 
       {this.state.currentList.map((item,i)=> 
        <BillsItem key ={i} value={item} /> 
       )} 
      </div> 
     ) 
    } 
}; 
+0

感謝您的想法之下,但它不工作,要麼 –

+0

它爲我工作。無論如何,你可以閱讀這個更多的信息:https://medium.com/@justintulk/react-anti-patterns-props-in-initial-state-28687846cc2e –

0

我覺得你的道具後,收到組件被初始化。所以在這種情況下,需要使用componentWillReceiveProps來更新狀態。 在你的情況下,它想

componentWillReceiveProps(nextProps) { 
    if(this.props.list !== nextProps.list) { 
    this.setState({ 
     currentList: nextProps.list, 
    }); 
    } 
} 
+0

非常感謝!它工作 但是,爲什麼它與String不適用於數組對象? –

+0

它不依賴於狀態。這取決於道具如何發送到組件。如果您的數據是從其他來源(如http)獲取的,則需要一段時間才能收到它,然後發送到組件。 – Panther