【问题标题】:How to filter data in ListView React-native?如何在 ListView React-native 中过滤数据?
【发布时间】:2017-07-27 10:00:29
【问题描述】:

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

我正在使用 Redux 将我的状态映射到 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);

我在这里做错了什么?

【问题讨论】:

    标签: javascript reactjs react-native redux


    【解决方案1】:

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

    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. 如果没有搜索词则跳过过滤。仅当列表非常大时才有意义。

    我有点担心的一点是,在组件内部进行获取,将其置于全局状态,然后依靠该组件对全局状态变化做出反应的模式。因此,更改全局状态成为简单查看某物的副作用。我假设您正在这样做,因为assets 在其他地方使用,这是从服务器刷新它们的方便点,以便它们显示在其他不获取它们的组件中。这种模式可能会导致难以发现的错误。

    【讨论】:

    • 有效!!太感谢了!!我所要做的就是在文本的构造函数中设置初始状态。 :) 谢谢蒂姆!
    • 哦,对了。否则状态本身是未定义的。很高兴它有效。
    • 我更新了答案。我使用 ES7 属性设置器而不是构造函数。
    【解决方案2】:

    您需要执行setState 来触发渲染。这是我的做法-

    constructor(props) {
      super(props);
      this.ds = new ListView.DataSource({ rowHasChanged: (r1,r2) => r1 !== r2 });
      this.state = {
        assets: []
      };
    }
    
    componentWillMount() {
      this.props.assetsFetch();
      this.setState({
        assets: this.props.assets
      });
    }
    
    componentWillReceiveProps(nextProps) {
      this.setState({
        assets: nextProps.assets
      });
    }
    
    onSearchChange(text) {
      const filteredAssets = this.props.assets.filter(asset => asset.name.indexOf(text) !== -1);
      this.setState({
        assets: _.values(filteredAssets)
      });
    }
    
    
    render() {
      ...
      <ListView
        dataSource={this.ds.cloneWithRows(this.state.assets)}
        .....
      />
    }
    

    【讨论】:

    • 但是我正在使用 redux 来管理我的状态。你认为这是做到这一点的方法吗?我认为我们根本不允许从组件级别更改 redux 的状态。
    • 这不是在 Redux 情况下处理此问题的正确方法。您要求我使用操作和调度程序从组件级别更改我处理状态的方式。
    • 这个答案的问题是如果用户在assetFetch完成之前输入搜索,搜索词将不会被应用。
    猜你喜欢
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 2019-02-11
    相关资源
    最近更新 更多