【问题标题】:I can't set an empty array in the state我无法在状态中设置空数组
【发布时间】:2019-06-12 00:17:29
【问题描述】:

我正在设置一个应用程序,并且在此应用程序中有一个列表,此列表中的项目有一个标题和一个用于删除项目的按钮,我可以删除几乎所有项目,但是当休息一个元素时我无法删除,但是我可以...我只是不能 setState 一个空数组。我正在使用 lodash 删除元素。

我尝试将新数组放入 aux var 并检查大小是否等于 0,然后直接将 setState 设置为空数组,而不是使用 remove 函数执行此操作。

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);

【问题讨论】:

  • 我听不懂你在说什么。能说清楚一点吗?
  • 我有一个包含 3 个元素的数组,在平面列表中设置等。要将数据设置为平面列表,我使用“状态”,所以当我一个一个删除元素时,最后一个我无法删除
  • 您在控制台中看到任何错误?
  • 我认为您正在传递 this.state.plates 根据 lodash 文档 lodash.com/docs/4.17.11#remove 的 const 类型尝试传递板块数组的本地副本以删除函数,然后检查大小并设置状态。
  • 没看懂,可以举个例子吗?

标签: javascript reactjs react-native lodash


【解决方案1】:

你为什么使用 lodash?它可以通过函数内置数组来完成。删除 lodash 函数正在改变状态变量,这在 React 中是不可接受的。

state = {
    items: [
      { name: "John", id: 1 },
      { name: "Paul", id: 2 },
      { name: "jonathan", id: 3 }
    ]
  };

  removeItem = id =>
    this.setState(prev => ({
      items: prev.items.filter(item => id !== item.id)
    }));

  render() {
    return (
      <div className="App">
        {this.state.items.map(item => (
          <div onClick={() => this.removeItem(item.id)} key={item.id}>
            remove {item.name} id {item.id}
          </div>
        ))}
      </div>
    );
  }

【讨论】:

  • 我认为这不是问题,即使我调用了 setState ({plates: []}),最后一个元素也发生了同样的事情
  • 我认为您应该根据我的建议进行一些更改。可能您的componentDidUpdate 是个问题。我没有沙箱,但如果我认为正确的话,this.props.placa 是数组中的一个元素。当组件更新并且状态中的数组为空(比较undefined 与元素)时,条件始终为真,您使用该元素更新新状态。如果 props 中的元素与组件状态中的元素相同,我是对的
  • 我认为你是对的,有道理。现在我有另一个问题-_-'
  • 什么问题?
  • 我必须清除道具以使 if 子句为假,所以我使用 Action.refresh({placa: undefined}) 并解决了我的问题:),谢谢
猜你喜欢
  • 1970-01-01
  • 2019-10-05
  • 1970-01-01
  • 2020-05-07
  • 2020-09-11
  • 2019-10-20
  • 2020-08-26
  • 2017-03-05
相关资源
最近更新 更多