数组过滤器不适用于状态

时间:2018-08-17 22:15:18

标签: javascript reactjs react-native

我有一个数组,它是一个状态,状态的值显示在视图中,我也有一个文本视图,我想使文本输入的值更改状态的值,以便状态视图会更改,但不会更改状态视图中的值, 也就是说,如果我输入a,则视图不会改变;如果我输入ab,则返回错误,提示undefined is not an object(evaluating item.toLowerCase) 请在哪里我可能错了

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      schools: [
        "Abubakar Tafawa Balewa University, Bauchi",
        "Ahmadu Bello University, Zaria",
        "Bayero University, Kano",
      ],
    };
    this.handleChange = this.handleChange.bind(this);
    this.schoolChange = this.schoolChange.bind(this);
  }

  schoolChange(text) {
    for (let i = 0; i < this.state.schools.length; i++) {
      console.log(this.state.schools[i]);
    }
    let c = this.state.schools.map(item => item.toLowerCase(item));
    let b = c.filter(item => item.indexOf(text) > -1);
    let d = b.map(item => item.toUpperCase(item));
    console.log(d);
    var len = d.length;
    for (let i = 0; i < len; i++) {
      let row = d[i];
      this.setState(
        prevState => ({
          schools: [...prevState.schools, row],
        }),
        console.log(this.state.schools[i]),
      );
    }
  }

  handleChange(text) {
    this.setState({ text }, () => {
      this.schoolChange(this.state.text);
    });
  }

  render() {
    const schools = this.state.schools.map((school, index) => (
      <Text style={styles.text}>{school}</Text>
    ));

    return (
      <View>
        <TextInput
          placeholder="Search"
          value={this.state.text}
          onChangeText={text => this.handleChange(text)}
        />
        <ScrollView overScrollMode={"never"} keyboardShouldPersistTaps="always">
          {schools}
        </ScrollView>
      </View>
    );
  }
}

2 个答案:

答案 0 :(得分:1)

这是因为您要覆盖学校数组,而现在没有要过滤的数据。您的数据源是this.state.schools,并且在过滤器上,您正在用新数据替换学校数组,也许是空数组,因此现在您没有办法将数据恢复为过滤器。因此,不要将源数据保留在状态中,而应将其保留在某些全局变量或this.schools中,以便更新状态不会更改源

保留数据副本。您无需在循环中设置setState。简单地计算数据,然后设置状态。

constructor(props) {
    super(props);
        this.schools = [
                   "Abubakar Tafawa Balewa University, Bauchi",
                   "Ahmadu Bello University, Zaria",
                   "Bayero University, Kano"
                ];
        this.state = {
                schools: this.schools
        }

    this.handleChange = this.handleChange.bind(this);
}
  
 handleChange(text){
     const schools = this.schools.filter(name => name.toLowerCase().indexOf(text.toLowerCase()) > -1);
     this.setState({ schools });
 }

答案 1 :(得分:1)

您还可以简化 schoolChange 函数:

schoolChange(text){
     const schools = this.schools.filter(school => school.toUpperCase().includes(text.toUpperCase()));
     this.setState({
       schools,
     });
 }