0
我是新来的人,我是新来的JavaScript。我的代码有问题,我似乎无法找到错误的位置。当按钮被点击时,React Native添加新数据
我的应用程序有一个用户可以添加和保存板号。问题是,每次我存盘或单击添加按钮或只是清楚地点击已保存的板块,它复制自身
这里是我的这一个
export default class plakaco extends Component {
constructor(){
super()
this.state = {
plates: [
{plateNumber: '', status: '', id: 1},
]
}
this.getPlateId = this.getPlateId.bind(this);
}
componentWillReceiveProps(nextProps) {
let newArr = this.state.plates.slice(0);
let idPlate = this.state.plates[this.state.plates.length - 1];
let newId = idPlate.id + 1
newArr.push({plateNumber: nextProps.pn, status: 'Saved', id: newId})
this.setState({
plates: newArr
})
}
componentDidMount() {
AsyncStorage.getItem("id").then(val => {
this.setState({
"id": val
})
fetch(`http://aaa.com/api/getClientPlates/${val}`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({})
}).then(response => {
response.json().then(data => {
console.log(data)
})
})
}).done()
}
getPlateId(i, plateNumber, inputEditable){
this.props.getValues(plateNumber, inputEditable, false, false);
}
addAPlate(){
this.props.getValues('', true, true, true);
}
render() {
return (
<View style={styles.leftView}>
<Button
onPress={this.addAPlate.bind(this)}
title="ADD"
color="#343434"
accessibilityLabel="Add a plate."
/>
<PlateItems plates={this.state.plates} getPlateId={this.getPlateId}/>
</View>
);
}
}
const styles = StyleSheet.create({
leftView: {
flex: 1,
backgroundColor: '#F1F1F1'
}
});
下面的代码是代码上在那里我点击了一个板,它保持了一遍又一遍添加相同的板
_onPress(i){
this.props.plates.filter((val) => {
if(val.id === i){
this.props.getPlateId(i, val.plateNumber, false, false);
}
});
}
render() {
const listItems = this.props.plates.map((item) =>
<TouchableOpacity onPress={this._onPress.bind(this, item.id)} key={item.id}>
<View style={styles.lists} >
<Text style={styles.itemText1}>{item.plateNumber}</Text>
<Text style={styles.itemText2}>{item.status}</Text>
</View>
</TouchableOpacity>
);
Here is a sample image of no plates added or saved
Sample Image with save plates that duplicates itself whenever it is click
非常感谢!
还是一样的爵士。当我点击一个现有的板块重复 – kurokocrunch
当你的item.id是唯一的,那么就没有必要使用过滤器..使用indexOf – Codesingh
什么? @Codesingh – kurokocrunch