React Native: я не могу поддерживать их состояние - PullRequest
0 голосов
/ 27 апреля 2018

У меня следующая проблема, у меня есть список флажков, и я не могу поддерживать их состояние, я должен создать массив в this.state, но он не сработало.

В этом фрагменте кода я зацикливаюсь на хранении флажков, которые будут отображаться на экране, в то же время в свойстве флажка я пытаюсь сохранить состояние флажка

 <Checkbox
            name={'check'+item.id_camada}
            checked={

  this.state  
  .checkBoxCheckedArray
  [this.state.checkBoxCheckedArray
  [this.props.name.replace("check","")].id].checked
            }
            size={30}
            style={{backgroundColor: '#f2f2f2', color:'blue', borderRadius: 
   5}}
            onChange={(name, checked) => 
   this._onSelectCamada(name,item.id_camada, checked)}/>

В этом другом разделе я пытаюсь изменить состояние флажка и включить маркеры после извлечения из базы данных

  _onSelectCamada=(name,value, checked) =>{

    this.state.checkBoxCheckedArray[value].checked = !checked;
    this.state.checkBoxCheckedArray[value].id = value;


    let formData = new FormData();
    formData.append('acao', 'getMarcadores');
    formData.append('id_camada', value);

    let options = {
        method: 'POST',
        headers: {
            Accept: 'multipart/form-data',
            'Content-Type': 'multipart/form-data',
        },
        body: formData,
    };

    fetch(URL + "/pesquisar_camada.php", options).then((response) => response.json())
        .then((responseJson) => {
            // console.log("log::"+responseJson);
            for (let json of responseJson) {
                this.markers.push(json);
            }

            this.setState({
                markers: this.markers,
                checkBoxCheckedArray:this.state.checkBoxCheckedArray
            });

        })
        .catch((error) => {

            console.error(error);

        });

     }

Полный код:

import React, {Component} from 'react';
import {
Text,
TextInput,
View,
StyleSheet,
TouchableHighlight,
Modal,
Alert,
Dimensions,
ScrollView,
Picker,
AsyncStorage
} from 'react-native';

import MapView, {PROVIDER_GOOGLE} from 'react-native-maps';
import {Toolbar, COLOR, ThemeProvider} from 'react-native-material-ui';
import CardView from 'react-native-cardview' ;
import deviceLog, {LogView, InMemoryAdapter} from 'react-native-device-log';
import FormData from 'FormData';
import {Button} from 'react-native-elements'
import Checkbox from 'react-native-custom-checkbox';

const uiTheme = {
palette: {
    primaryColor: COLOR.blue500,
},
toolbar: {
    container: {
        height: 50,
    },
},
 };

  const {width, height} = Dimensions.get('window');

  const ASPECT_RATIO = width / height;
  const LATITUDE_DELTA = 0.0922;
  const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
  const LATITUDE = -1.444892;
  const LONGITUDE = -48.468348;
  let URL = "http://mentorsites.com.br/w3gcon_mapas";


  deviceLog.init(AsyncStorage /* You can send new InMemoryAdapter() if you do not want to persist here*/
, {
    //Options (all optional):
    logToConsole: false, //Send logs to console as well as device-log
    logRNErrors: true, // Will pick up RN-errors and send them to the device log
    maxNumberToRender: 2000, // 0 or undefined == unlimited
    maxNumberToPersist: 2000 // 0 or undefined == unlimited
}).then(() => {

//When the deviceLog has been initialized we can clear it if we want to:
//deviceLog.clear();

});

//The device-log contains a timer for measuring performance:
deviceLog.startTimer('start-up');

  export default class App extends Component {
   constructor(props) {
    super(props);
    this.state = {
        markers: [],
        isPainelCamadaVisivel: false,
        areas: [],
        camadas: [],
        check:false,
        checkBoxCheckedArray : []
    };
    this.mapRef = null;
    this.markers = [];
    this.checkBoxArray = [];

   }

   componentDidMount() {

    setTimeout(function () {
        fetch(URL + '/lista_areas.php')
            .then((response) => response.json())
            .then((responseJson) => {
                this.setState({
                    areas: responseJson
                });
            })
            .catch((error) => {
                console.error(error);
            });
    }.bind(this), 3000);
    };

  renderIf = (condition, content) => {
    if (condition) {
        return content;
    } else {
        return null;
    }
  };

  clickBtnFecharDialogBusca = () => {
    this.setState({
        isPainelCamadaVisivel: false
    });

    if (this.getLatLng().length > 0) {
        this.mapRef.fitToCoordinates(this.getLatLng(), {
            edgePadding: {
                top: 10,
                right: 10,
                bottom: 10,
                left: 10
            }, animated: false
        })
    }
   }

  _onSelectCamada=(name,value, checked) =>{

    this.state.checkBoxCheckedArray[value].checked = !checked;
    this.state.checkBoxCheckedArray[value].id = value;


    let formData = new FormData();
    formData.append('acao', 'getMarcadores');
    formData.append('id_camada', value);

    let options = {
        method: 'POST',
        headers: {
            Accept: 'multipart/form-data',
            'Content-Type': 'multipart/form-data',
        },
        body: formData,
    };

    fetch(URL + "/pesquisar_camada.php", options).then((response) => response.json())
        .then((responseJson) => {
            // console.log("log::"+responseJson);
            for (let json of responseJson) {
                this.markers.push(json);
            }

            this.setState({
                markers: this.markers,
                checkBoxCheckedArray:this.state.checkBoxCheckedArray
            });

        })
        .catch((error) => {

            console.error(error);

        });

     }

   onValueChangeEscolhaArea(itemValue, itemIndex) {
    this.setState({PickerValue: itemValue});
    if (itemValue && itemValue != "-1") {


        let formData = new FormData();
        formData.append('acao', 'listar');
        formData.append('id_grupo', itemValue);

        this.checkBoxArray = [];

        let options = {
            method: 'POST',
            headers: {
                Accept: 'multipart/form-data',
                'Content-Type': 'multipart/form-data',
            },
            body: formData,
        };

        fetch(URL + "/pesquisar_camada.php", options).then((response) => response.json())
            .then((responseJson) => {
                this.setState({camadas: responseJson});
            })
            .catch((error) => {
                console.error(error);
            });


    }
}

getLatLng = () => {
    markersTmp = [];
    for (let marker of this.state.markers) {
        markersTmp.push({latitude: marker.lat, longitude: marker.lng});
    }

    return markersTmp;

};

render() {
    let areasItems = this.state.areas.map((item, index) => {
        return <Picker.Item key={item.id} value={item.id} label={item.nome_grupo}/>
    });

    areasItems.unshift(<Picker.Item key="-1" value="-1" label="-Selecione a área-"/>);

    let camadasItems = [];
    for(let item of this.state.camadas){
        this.state.checkBoxCheckedArray[item.id_camada]={
            id:0,
            checked:false
        };

        let checkbox = <Checkbox
            name={'check'+item.id_camada}
            checked={
               this.state.checkBoxCheckedArray[this.state.checkBoxCheckedArray[this.props.name.replace("check","")].id].checked
            }
            size={30}
            style={{backgroundColor: '#f2f2f2', color:'blue', borderRadius: 5}}
            onChange={(name, checked) => this._onSelectCamada(name,item.id_camada, checked)}/>;

        camadasItems.push(

            <View style={{flex: 1, flexDirection: 'row'}}>
                <View style={{width: "10%"}}>
                    {checkbox}
                </View>
                <View style={{width: "80%", paddingTop: 13}}>
                    <Text>
                        {item.nome_camada}
                    </Text>
                </View>
            </View>
        );
    }

    return (

        <View style={styles.container}>

            <MapView
                provider={this.props.provider}
                ref={(ref) => {
                    this.mapRef = ref
                }}
                onLayout={() => {

                }

                }
                initialRegion={{
                    latitude: LATITUDE,
                    longitude: LONGITUDE,
                    latitudeDelta: LATITUDE_DELTA,
                    longitudeDelta: LONGITUDE_DELTA
                }}

                style={styles.mapView}
            >
                {this.state.markers.map(marker => (
                    <MapView.Marker
                        key={marker.id}
                        title={marker.titulo}
                        coordinate={{latitude: marker.lat, longitude: marker.lng}}
                        description={marker.descricao}
                    />
                ))
                }
            </MapView>


            {this.renderIf(this.state.isPainelCamadaVisivel,


                <View ref={painelSelecaoCamada => this._painelSelecaoCamada = painelSelecaoCamada}
                      style={styles.bgFull}>
                    <ScrollView style={stylesCard.scrollCard}>
                        <View style={stylesCard.viewCard}>
                            <View style={styles.borderPicker}>
                                <Picker
                                    style={styles.pickerArea}
                                    selectedValue={this.state.PickerValue}
                                    onValueChange={(itemValue, itemIndex) => {

                                        this.onValueChangeEscolhaArea(itemValue, itemIndex);
                                    }
                                    }//fim
                                >
                                    {areasItems}
                                </Picker>
                            </View>
                            <View style={{height: 20}}>

                            </View>
                            <Button
                                backgroundColor="#1565C0"
                                onPress={() => {
                                    this.clickBtnFecharDialogBusca();
                                }}
                                title="Ok"
                                buttonStyle={{width: 300, height: 50}}

                            ></Button>
                            <View style={{height: 20}}>
                            </View>
                            {camadasItems}

                        </View>
                    </ScrollView>
                </View>
            )}

            <ThemeProvider uiTheme={uiTheme}>

                <View style={styles.inputView}>

                    <Toolbar
                        key="toolbar"
                        ref={(toolbar) => this._toolbar = toolbar}
                        leftElement="menu"
                        centerElement="Pesquise"

                        searchable={{
                            autoFocus: true,
                            placeholder: 'Search',
                            onChangeText: (text) => {
                                if (this.state.PickerValue == "-1") {
                                    Alert.alert(
                                        'Aviso',
                                        'Selecione primeiro uma área na caixa de listagem abaixo',
                                        [
                                            {text: 'OK', onPress: () => console.log('OK Pressed')},
                                        ],
                                        {cancelable: false}
                                    );
                                } else {


                                    fetch(URL + "/pequisar_area.php", {
                                        method: 'POST',
                                        headers: {
                                            Accept: 'application/json',
                                            'Content-Type': 'application/json',
                                        },
                                        body: JSON.stringify({
                                            acao: "pesquisarPorTituloEDescricao",
                                            id_area: this.state.PickerValue,
                                            busca: text,
                                        }),
                                    }).then((response) => response.json())
                                        .then((responseJson) => {
                                            return responseJson.movies;
                                        })
                                        .catch((error) => {
                                            console.error(error);
                                        });
                                }
                            },
                            onSearchPressed: function () {
                                this.setState({
                                    isPainelCamadaVisivel: true
                                });

                            }.bind(this),
                            onSearchClosed: function () {
                                this.setState({
                                    isPainelCamadaVisivel: false
                                });
                                //this.handleSearchClosed.bind(this);



                            }.bind(this)
                        }}
                    />

                </View>
            </ThemeProvider>
        </View>
    );



    /*<LogView inverted={false} multiExpanded={true} timeStampFormat='HH:mm:ss'></LogView>*/
}


}

 const styles = StyleSheet.create({
 containerToolbar: {
    paddingTop: 16,
 },
container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#F5FCFF',
},
mapView: {
    position: 'absolute',
    top: 0,
    left: 0,
    bottom: 0,
    right: 0
},
inputView: {
    backgroundColor: 'white',
    borderWidth: 1,
    borderColor: '#CCC',
    borderRadius: 3,
    position: 'absolute',
    top: 10,
    left: 5,
    right: 5
},
bgFull: {
    width: '100%',
    height: '100%',
    position: 'absolute',
    top: 0,
    bottom: 0,
    left: 0,
    backgroundColor: '#F5FCFF',
    paddingTop: 70,
    alignItems: "center",
    display: "none"
},
pickerArea: {

    width: '100%'
},
borderPicker: {
    borderWidth: 1,
    borderColor: '#CCC',
    borderRadius: 3,
    width: '80%',
    backgroundColor: "#FFF"
 }
 });

const stylesCard = StyleSheet.create({

MainContainer: {

    flex: 1,
    backgroundColor: '#F5FCFF',
    justifyContent: 'center',
    alignItems: 'center',

},

cardViewStyle: {

    width: "100%",
    height: 150,
    marginLeft: 10,
    marginRight: 10

},

cardView_InsideText: {

    fontSize: 20,
    color: '#000',
    textAlign: 'center',
    marginTop: 50

},
scrollCard: {
    width: "100%"
},
viewCard: {
    width: "100%",
    alignItems: "center"
}

});

Может ли кто-нибудь мне помочь?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...