我试图在带有tsx的reactjs中过滤具有多个键值的数据。 Cards.tsx是父组件,而ShipmentCard.tsx是子组件。我收到Property 'toLowerCase' does not exist on type 'never'错误。我只想根据搜索条件返回相关对象。谁能让我知道我在哪里犯错了?

Cards.tsx



class Cards extends Component {
  state = {
    card: [],
    filter: ""
  };

  componentDidMount() {
    this.loadShipmentList();
  }

  handleChange = (event: any) => {
    this.setState({ filter: event.target.value });
  };

  loadShipmentList() {
    fetch("http://localhost:3001/shipments")
      .then(response => response.json())
      .then(data => this.setState({ card: data }));
  }

  render() {
    const { card, filter } = this.state;
    const lowercasedFilter = filter.toLowerCase();
    const filteredData = this.state.card.filter(item => {
      return Object.keys(item).some(key =>
        item[key].toLowerCase().includes(lowercasedFilter)
      );
    });

    return (
        <Card className="Search-Bar">
          <CardContent>
            <Grid container spacing={3}>
                <TextField
                  label="Search"
                  onChange={this.handleChange}
                />
            </Grid>
          </CardContent>
        </Card>
        <Grid container spacing={3}>
          {filteredData.map((card: any) => (
            <Grid item xs={12}>
              <ShipmentCard key={card.id} value={card} />
            </Grid>
          ))}
        </Grid>
    );
  }
}

export default Cards;




db.json



{
  "shipments": [
    {
      "id": "123",
      "name": "Heromisha",
      "total": "1000",
      "status": "ACTIVE",
      "userId": "E222"
    },
    {
      "id": "456",
      "name": "Honda",
      "total": "3000",
      "status": "ACTIVE",
      "userId": "E111"
    }
  ]
}

最佳答案

编译器不是state.card [...]的真实类型,因为它被声明为数组。
最简单的方法是将其声明为any []

  state = {
    card: [] as any[],
    filter: ""
  };


或显式描述数据类型

interface Card {
    "id": string,
    "name": string,
    "total": string,
    "status": string,
    "userId": string
}
...
      state = {
        card: [] as Card[],
        filter: ""
      };


或通过对象示例

const cardSample = {
      "id": "123",
      "name": "Heromisha",
      "total": "1000",
      "status": "ACTIVE",
      "userId": "E222"
  };

type Card = typeof cardSample;

    ...
          state = {
            card: [] as Card[],
            filter: ""
          };

10-07 20:39