javascript - 如何在 ListView React-native 中过滤数据?

标签 javascript reactjs react-native redux

我正在尝试过滤我的数组对象列表,然后尝试使用新数据源在 ListView 中显示。但是,该列表未被过滤。我知道我的过滤器功能正常工作。 (我在 console.log 里查过了)

我正在使用 Redux 将我的状态映射到 prop。然后尝试过滤 Prop 。这是错误的方法吗?

这是我的代码:

/*global fetch:false*/
import _ from 'lodash';
import React, { Component } from 'react';
import { ListView, Text as NText } from 'react-native';
import { connect } from 'react-redux';
import { Actions } from 'react-native-router-flux';
import {
  Container, Header, Item,
  Icon, Input, ListItem, Text,
  Left, Right, Body, Button
} from 'native-base';


import Spinner from '../common/Spinner';
import HealthImage from '../misc/HealthImage';
import { assetsFetch } from '../../actions';

const ds = new ListView.DataSource({
  rowHasChanged: (r1, r2) => r1 !== r2
});

class AssetsList extends Component {
  componentWillMount() {
    this.props.assetsFetch();

    // Implementing the datasource for the list View
    this.createDataSource(this.props.assets);
  }

  componentWillReceiveProps(nextProps) {
    // Next props is the next set of props that this component will be rendered with.
    // this.props is still equal to the old set of props.
    this.createDataSource(nextProps.assets);
  }

  onSearchChange(text) {
    const filteredAssets = this.props.assets.filter(
      (asset) => {
        return asset.name.indexOf(text) !== -1;
      }
    );

    this.dataSource = ds.cloneWithRows(_.values(filteredAssets));
  }

  createDataSource(assets) {
    this.dataSource = ds.cloneWithRows(assets);
  }


  renderRow(asset) {
    return (
      <ListItem thumbnail>
          <Left>
              <HealthImage health={asset.health} />
          </Left>
          <Body>
              <Text>{asset.name}</Text>

              <NText style={styles.nText}>
                Location: {asset.location} |
                Serial: {asset.serial_number}
              </NText>
              <NText>
                Total Samples: {asset.total_samples}
              </NText>

          </Body>
          <Right>
              <Button transparent onPress={() => Actions.assetShow()}>
                  <Text>View</Text>
              </Button>
          </Right>
      </ListItem>
    );
  }



  render() {
    return (
     <Input
                  placeholder="Search"
                  onChangeText={this.onSearchChange.bind(this)}
                />
        <ListView
          enableEmptySections
          dataSource={this.dataSource}
          renderRow={this.renderRow}
        />


    );
  }
}

const mapStateToProps = state => {
  return {
    assets: _.values(state.assets.asset),
    spinner: state.assets.asset_spinner
  };
};

export default connect(mapStateToProps, { assetsFetch })(AssetsList);

我在这里做错了什么?

最佳答案

要理解这里发生的事情有点困难。我会把它简化成这样:

class AssetsList extends Component {
  state = {};

  componentDidMount() {
    return this.props.assetsFetch();
  }

  onSearchChange(text) {
    this.setState({
      searchTerm: text
    });
  }

  renderRow(asset) {
    return (
      <ListItem thumbnail>
          <Left>
              <HealthImage health={asset.health} />
          </Left>
          <Body>
              <Text>{asset.name}</Text>

              <NText style={styles.nText}>
                Location: {asset.location} |
                Serial: {asset.serial_number}
              </NText>
              <NText>
                Total Samples: {asset.total_samples}
              </NText>

          </Body>
          <Right>
              <Button transparent onPress={() => Actions.assetShow()}>
                  <Text>View</Text>
              </Button>
          </Right>
      </ListItem>
    );
  }

  getFilteredAssets() {

  }

  render() {
    const filteredAssets = this.state.searchTerm
      ? this.props.assets.filter(asset => {
          return asset.name.indexOf(this.state.searchTerm) > -1;
        })
      : this.props.assets;
    const dataSource = ds.cloneWithRows(filteredAssets);
    return (
     <Input
                  placeholder="Search"
                  onChangeText={this.onSearchChange.bind(this)}
                />
        <ListView
          enableEmptySections
          dataSource={dataSource}
          renderRow={this.renderRow}
        />
    );
  }
}

const mapStateToProps = state => {
  return {
    assets: _.values(state.assets.asset),
    spinner: state.assets.asset_spinner
  };
};

export default connect(mapStateToProps, { assetsFetch })(AssetsList);

几点:

  1. 您的组件是有状态的。有一种状态只属于组件:搜索词。将其保持在组件状态。
  2. 不要更改生命周期函数中的数据源。在您知道需要的最新点上进行:在渲染中。
  3. 我猜 assetFetch 中有一些异步的东西,所以你可能应该在 componentDidMount 中返回它。
  4. 我从 componentWillMount 更改为 componentDidMount。推荐放异步抓取componentDidMount。如果您做过服务器端渲染,这可能很重要。
  5. 如果没有搜索词,则跳过过滤。这仅在列表非常大时才有意义。

我有点担心的一件事是获取组件内部的模式,将其置于全局状态,然后依赖该组件对全局状态变化使用react。因此,改变全局状态成为简单查看某些东西的副作用。我假设您这样做是因为 assets 在别处使用,这是从服务器刷新它们的一个方便点,这样它们就会出现在不获取它们的其他组件中。这种模式可能会导致难以发现的错误。

关于javascript - 如何在 ListView React-native 中过滤数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42644161/

相关文章:

javascript - 如何在 Immutable.Map({}) 中更改 ImmutableList({}) 中项目的属性

android - 我无法在默认 'Welcome to React Native!"APP 中使用辅助功能

javascript - expo sdk 40 metro.config.js "Expected ' fromDir' 为 'string' ,得到 'undefined' “

react-native - 无法在原子中生成命令

javascript - 就良好实践而言,带有闭包的 javascript 原型(prototype)是一件好事吗

javascript - 显示矩阵编辑器输出

node.js - "offset"的值超出范围。它必须 >= 0 && <= 17825792

javascript - 获取变换后旋转物体的宽高

javascript - 为什么在 js 中运行两个单独的循环与运行单个 for 循环之间存在性能差异

javascript - 出于某种原因,无法使用 Reactjs 中的 axios 从 api 获取数据以在屏幕上呈现