2017-06-21 65 views
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

非常感謝!

回答

0

理解我想出了一個解決方案的代碼的錯誤可能是componentWillReceiveProps並請更改

this.state.plates[this.state.plates.length - 1]; 

to 

newArr[newArr.length - 1]; 

乾杯:)

+0

還是一樣的爵士。當我點擊一個現有的板塊重複 – kurokocrunch

+0

當你的item.id是唯一的,那麼就沒有必要使用過濾器..使用indexOf – Codesingh

+0

什麼? @Codesingh – kurokocrunch