2016-08-26 118 views
1

我想創建兩個表,我可以將數據拉入父組件,將數據傳遞到一個表中,並允許將數據從一個表移動到另一個表。所以我需要能夠爲所有AJAX數據創建一個表格,然後爲所選數據創建一個表格。我無法通過道具傳遞數據,因爲一旦AJAX請求完成,孩子不會更新。 (基本上父組件觀察和兩個孩子之間共享數據。)如何通過道具傳遞AJAX數據給孩子

我已經嘗試了「WillReceive」和「WillUpdate」風格的文檔的方法,但他們從來不叫,我嘗試更新狀態

這裏是(我假裝對於現在的數據)

getInvoiceData(){ 
    return new Promise(function(resolve, reject) { 
     console.log("hi"); 
     resolve([{number: "1"},{number: "2"},{number: "3"}]); 
    }) 

} 

繼承人,我用REQ請求

componentDidMount() { 
    const self = this; 
    self.getInvoiceData() 
     .then((response) => { 
      self.state.invoices = response; 
      console.log(self.state); 
     }) 
     .catch((err) => { 
      console.error(err); 
     }) 
} 

我的繼承人渲染

render() { 
    return (
     <div> 
      <p>Selected: 
       { 
        function() {return JSON.parse(this.selected)} 
       } 
      </p> 
      <InvoicePickTable invoices = {this.state.invoices} selected = {this.selected} /> 
      <button>Move</button> 
      <InvoiceSelectedTable selectedInvoices = {this.state.selectedInvoices} /> 
     </div> 

    ); 
} 

繼承人我的孩子

import React from 'react'; 

class InvoicePickTable extends React.Component { 

    constructor(props) { 
     console.log("constructor called"); 
     super(props); 
     this.state = {invoices: []}; 
    } 
    selectInvoice(invoice) { 
     this.props.selected = invoice; 
    } 

    //never gets called 
    componentWillUpdate(nextProps, nextState) { 
     console.log(nextProps); 
     console.log(nextState) 
     console.log("eyy lmao"); 
     this.state.invoices = nextProps.invoices; 
     this.state.hasDate = true; 
    } 
    //never gets called 
    componentWillReceiveProps(nextProps) { 
     console.log(nextProps); 
     console.log("eyy lrofl"); 
     this.state.invoices = nextProps.invoices; 
    } 

    render() { 
     return (
      <table> 
       <thead> 
        <tr> 
         <th>Invoice #</th> 
         <th>Task Price</th> 
         <th>Balance</th> 
         <th>Task Name</th> 
         <th><button onClick={()=>{console.log(this.props);console.log(this.state)}}>props</button></th> 
        </tr> 
       </thead> 
       <tbody> 
       { 

        this.props.invoices.map(function (invoice) { 
         console.log("in"); 
         console.log(invoice); 
         return (
          <tr key = {invoice.number} onClick={this.selectInvoice(invoice)}> 
           <td>{invoice.number}</td> 
          </tr> 
         ); 
        }) 
       } 
       </tbody> 
      </table> 
     ); 
    } 

} 

export default InvoicePickTable; 

回答

0

更新必須使用setState()功能狀態,請試試這個:

componentDidMount() { 
     const self = this; 
     self.getInvoiceData() 
      .then((response) => { 


       this.setState({ 
        invoices : response 
       }); 
      }) 
      .catch((err) => { 
       console.error(err); 
      }) 
    } 
0

的訣竅是不要在家長直接操作的狀態,而是使用的setState({})功能。