【问题标题】:I'm not able to reset my state array after I click a button单击按钮后,我无法重置状态数组 [已解决]
【发布时间】:2022-10-07 21:41:26
【问题描述】:
  const initialState = [...properties];
  const [location, setLocation] = useState('');
  const [startDate, setStartDate] = useState(new Date());
  const formattedDate = moment(`${startDate}`).format('MM/DD/YYYY');
  const [price, setPrice] = useState('');
  const [propertyType, setPropertyType] = useState('');
  const [filteredProperties, setFilteredProperties] = useState(properties);

  const resetState = () => {
    setFilteredProperties([...initialState]);

  };

我正在尝试构建一个过滤器,如图所示。我想在每次单击搜索时重置状态,然后通过重置状态进行过滤,但是每次单击提交时它都会过滤数组,并且在第二次提交时永远不会重置,因此数组保持不变或变为空,具体取决于第二次过滤搜索.

完整代码在这里:https://github.com/Quelaan1/real_estate_search_filter/blob/develop/src/Components/Filter/Filter.tsx

https://i.stack.imgur.com/TNqYW.png

【问题讨论】:

  • 请分享properties 的来源以及更改/更新的位置。
  • 属性源自具有对象数组的 JSON。包含 RealEstate 属性详细信息的对象。 filter 函数应该根据页面上使用的过滤器过滤数组。

标签: reactjs react-hooks


【解决方案1】:

发生这种情况是因为状态需要时间来设置值。您可以尝试在组件末尾将状态设置为初始值。

function filterer() {
  
  console.log(propertyType);

if (startDate) {
  setFilteredProperties(
    properties.filter(
      (property) =>
        !moment(`${formattedDate}`, 'MM/DD/YYYY').isBetween(
          moment(property.notAvailabeOn[0], 'MM/DD/YYYY'),
          moment(property.notAvailabeOn[1], 'MM/DD/YYYY')
        )
    )
  );
}

if (price) {
  console.log(filteredProperties);
  setFilteredProperties(
    properties.filter(
      (property) =>
        property.price >= parseInt(price.split('-')[0]) &&
        property.price <= parseInt(price.split('-')[1])
    )
  );
}

if (location) {
  setFilteredProperties(
    properties.filter((property) =>
      property.location.toLowerCase().includes(location.toLowerCase())
    )
  );
}

if (propertyType) {
  setFilteredProperties(
    properties.filter((property) => property.propertyType === propertyType)
  );
}
setFilteredProperties([...properties]);
}

【讨论】:

  • 我希望它在过滤之前重置。
猜你喜欢
  • 1970-01-01
  • 2014-01-29
  • 2021-05-29
  • 2021-09-17
  • 1970-01-01
  • 2021-07-06
  • 2017-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多