Я не могу установить пустой массив в состоянии - PullRequest
0 голосов
/ 17 января 2019

Я настраиваю приложение, и в этом приложении есть список, элементы в этом списке имеют заголовок и кнопку, чтобы удалить элемент, я могу удалить почти весь элемент, но когда остаюсь один элемент, я не могу удалить, но Я могу ... Я просто не могу setState пустой массив. Я использую lodash для удаления элементов.

Я пытался поместить новый массив в переменную aux и проверить, равен ли его размер нулю, и установить для этого пустой массив вместо функции удаления.

class FuelReservesFilterView extends React.Component {
  state = { plates: [] };

  goToOperationsSearch = () => {
    Actions.selectOperationView({
      backSceneKey: "fuelReservesFilterView",
    });
  };

  goToPlateSearch = () => {
    Actions.selectPlateView({
      backSceneKey: "fuelReservesFilterView",
    });
  };

  goToStatusSearch = () => {
    Actions.selectStatusVehicleView({
      backSceneKey: "fuelReservesFilterView",
    });
  };

  componentDidUpdate() {
    if (this.props.placa) {
      if (_.last(this.state.plates) != this.props.placa) {
        this.setState({
          plates: [...this.state.plates, this.props.placa],
        });
      }
    }
  }

  renderBtnOperacao() {
    if (!this.props.operacao)
      return (
        <ButtonRounded
          onPress={this.goToOperationsSearch}
          textColor={ACCENT_COLOR}
          label={i18n.t("Select_operation")}
        />
      );
    else
      return (
        <TouchableOpacity onPress={this.goToOperationsSearch}>
          <View>
            <TextTitle style={styles.textStyle}>
              {this.props.operacao.nome}
            </TextTitle>
          </View>
        </TouchableOpacity>
      );
  }

  renderBtnStatus() {
    if (!this.props.status)
      return (
        <ButtonRounded
          onPress={this.goToStatusSearch}
          textColor={ACCENT_COLOR}
          label={i18n.t("Select_status_vehicle")}
        />
      );
    else
      return (
        <TouchableOpacity onPress={this.goToStatusSearch}>
          <View>
            <TextTitle style={styles.textStyle}>
              {this.props.status.nome}
            </TextTitle>
          </View>
        </TouchableOpacity>
      );
  }

  renderPlateItem({ item }) {
    return (
      <ClearItem
        withIcon
        onPressIcon={() => {
          this.removerItem(item);
        }}
        id={item.id}
        text={item.placa}
        icon="close"
      />
    );
  }

  removerItem = item => {  
      this.setState({ plates: _.remove(this.state.plates, function(plate) {
          return plate.placa != item.placa;
       })
    });
  };

  renderPlatesList() {
    if (_.size(this.state.plates) > 0) {
      return (
        <FlatList
          style={this.props.style}
          data={this.state.plates}
          renderItem={this.renderPlateItem.bind(this)}
          keyExtractor={plate => plate.placa}
        />
      );
    }
  }

  render() {
    return (
      <ScrollView style={styles.container}>
        <ButtonRounded
          onPress={this.goToPlateSearch}
          textColor={ACCENT_COLOR}
          label={i18n.t("Select_plate")}
        />
        {this.renderPlatesList()}
        <Divider space={20} />
        {this.renderBtnOperacao()}
        <Divider space={20} />
        {this.renderBtnStatus()}
        <Divider space={20} />
        <TextTitle>{i18n.t("Minimal_level")}</TextTitle>
        <CustomSlider
          min={0}
          max={100}
          metric="%"
          onValueChange={value => console.log(value)}
        />
        <TextTitle>{i18n.t("Maximum_level")}</TextTitle>
        <CustomSlider
          min={0}
          max={100}
          value={100}
          metric="%"
          onValueChange={value => console.log(value)}
        />
        <Divider space={20} />
        <ButtonRounded
          style={{ marginBottom: 50 }}
          textColor={PRIMARY_COLOR}
          label={i18n.t("Apply_filter")}
        />
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    padding: PADDING_VIEW,
  },
  textStyle: {
    textAlign: "center",
  },
});

const mapStateToProps = state => {
  return {};
};

export default connect(
  mapStateToProps,
  {},
)(FuelReservesFilterView);

1 Ответ

0 голосов
/ 17 января 2019

Почему вы используете lodash? Это можно сделать с помощью встроенных функций массивов. Функция удаления lodash изменяет переменную состояния, что является недопустимым в React. Я подготовил пример https://codesandbox.io/s/zk30qz5513

...