2016-09-22 12 views
0

我正在使用提取在React中執行Ajax請求。該請求工作正常,但即使我指定了唯一的密鑰,但出現錯誤。這裏是警告信息:使用反饋中的提取的Ajax請求

警告:數組或迭代器中的每個孩子都應該有一個唯一的「key」屬性。檢查Table的渲染方法。

任何想法,爲什麼我會得到這個錯誤?

我的代碼:

let Table = React.createClass({ 
    getInitialState: function(){ 
     return { 
      accounts: [{ 
       "product": "Fixed Saver", 
       "interestRate": 2.20, 
       "minimumDeposit": 500, 
       "interestType": "Fixed" 
      }] 
     } 
    }, 
    componentDidMount: function(){ 
     fetch('http://localhost/table/json/accounts.json') 
      .then(response => { 
       return response.json() 
      }) 
      .then(json => { 
       this.setState({accounts: json}) 
      }); 
    }, 
    render: function(){ 
     return (
      <div className="container"> 
       <ul className="header clearfix"> 
        <li>Product</li> 
        <li>Interest rate</li> 
        <li>Minimum deposit</li> 
        <li>Interest type</li> 
       </ul> 

       {this.state.accounts.map(account => { 
       return (
        <div className="account clearfix"> 
         <div key={account.id}>{account.product}</div> 
         <div>{account.interestRate} %</div> 
         <div>£ {account.minimumDeposit}</div> 
         <div>{account.interestType}</div> 
        </div> 
        ) 
       })} 
      </div> 
     ) 
    } 
}); 

let App = React.createClass({ 
    render: function(){ 
     return(
      <Table /> 
     ); 
    } 
}); 

ReactDOM.render(<App />, document.getElementById('table')); 

JSON文件

[ 
    { 
     "id": 1, 
     "product": "Fixed Saver", 
     "interestRate": 2.20, 
     "minimumDeposit": 500, 
     "interestType": "Fixed" 
    }, 
    { 
     "id": 2, 
     "product": "Fixed Saver", 
     "interestRate": 1.50, 
     "minimumDeposit": 0, 
     "interestType": "Tracker" 
    }, 
    { 
     "id": 3, 
     "product": "Offset Saver", 
     "interestRate": 1.8, 
     "minimumDeposit": 1000, 
     "interestType": "Fixed" 
    } 
] 

[增訂]

看起來陣營不喜歡我由於某種原因,唯一的ID。我已經添加一個索引地圖和現在的作品:

{this.state.accounts.map((account,i) => { 
    return (
     <div className="account clearfix" key={i}> 
      <div key={account.id}>{account.product}</div> 
      <div>{account.interestRate} %</div> 
      <div>£ {account.minimumDeposit}</div> 
      <div>{account.interestType}</div> 
     </div> 
    ) 
})} 

也意識到在getInitialState,對象的「賬戶」的陣列缺少財產「ID」,這可能是爲什麼我在的原因這個問題擺在首位。

回答

0

爲您的帳戶信息創建組件。

const Account = ({ account }) => (
    <div className="account clearfix"> 
    <div key={account.id}>{account.product}</div> 
    <div>{account.interestRate} %</div> 
    <div>£ {account.minimumDeposit}</div> 
    <div>{account.interestType}</div> 
    </div> 
); 

然後映射數據數組是這樣的:

{this.state.accounts.map(account => <Account key={account.id} account={account} />)} 
+0

嘿安迪,感謝您的快速反應。剛剛嘗試過,仍然收到相同的錯誤。 – John

+0

如果你檢查道具,你是否看到每個div都有一個唯一的'key'? –

+0

不,你是對的 - 由於某種原因,唯一的關鍵不被附加。 – John