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'属性,请看我的编辑 –