2
我已經在ReactJS中編寫了一個簡單的代碼,其中我通過將狀態數據和updateState函數作爲道具傳遞給Store組件來調用View組件。然後View組件通過傳遞相同的兩個道具來調用Action組件。 Action組件修改Store組件的狀態並調用它的函數updateState來修改狀態。ReactJS屏幕上未顯示新添加的項目
現在的問題是新添加的項目沒有顯示在屏幕上可見的列表中。而且我收到一個錯誤(下面給出)。那麼請告訴我的代碼有什麼問題?
錯誤:
index.js:1017 Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `View`. See fb.me/react-warning-keys for more information.
in li (created by View)
in View (created by Store)
in div (created by Store)
in Store
Store.jsx
import React from 'react';
import View from './View.jsx';
class Store extends React.Component {
constructor(props) {
super(props);
this.state = {
data:
[
{
name: 'First',
id: 1
},
{
name: 'Second',
id: 2
},
{
name: 'Third',
id: 3
}
]
}
this.updateState = this.updateState.bind(this);
};
updateState(newState) {
this.setState({data: newState});
};
render() {
return (
<div>
<View storeData={this.state.data} func={this.updateState} />
</div>
);
}
};
export default Store;
View.jsx
import React from 'react';
import Action from './Action.jsx';
class View extends React.Component {
render() {
return (
<div>
<ul>
{this.props.storeData.map((eachObject) => (
<li key={eachObject.id}>{eachObject.name}</li>))}
</ul>
<Action storeData={this.props.storeData} func={this.props.func} />
</div>
);
}
}
export default View;
Action.jsx
import React from 'react';
let itemIndex=3;
class Action extends React.Component {
constructor() {
super();
this.updateStore = this.updateStore.bind(this);
};
render() {
return (
<div>
<input type="text" ref="input"/>
<button onClick={this.updateStore}>Add</button>
</div>
);
};
updateStore(e) {
const node = this.refs.input;
const text = node.value.trim();
node.value = '';
node.focus();
++itemIndex;
var newItem = {itemIndex, text};
var storeData = this.props.storeData;
storeData.push(newItem);
this.props.func(storeData);
}
}
export default Action;
仍然面臨同樣的問題。 – Agha
問題是'id',也是'name'屬性,請看我的編輯 –