我是新来的本地反应,我是javascript的新手。我的代码有问题,我似乎无法找到错误的位置。
我的应用有一个用户可以添加和保存板号。问题是我每次保存印版或点击添加按钮或只是简单地点击已经保存的印版,它会复制自己
这是我的代码
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
非常感谢你!
答案 0 :(得分:0)
在理解了代码后,我想出了一个错误可能在componentWillReceiveProps
中的解决方案,请更改
this.state.plates[this.state.plates.length - 1];
to
newArr[newArr.length - 1];
干杯:)