首页 > 解决方案 > 当我在搜索中输入内容时如何更新我的列表?

问题描述

 search = () => {
      fetch(strings.baseUri+"search_by_name", {
       method: 'POST',
       headers: {
              Accept: 'application/json',
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({ 
              "name": this.state.name,
            })
          })
          .then((response) => response.json())
          .then((responseJson) => {

             this.setState({data: responseJson});     

         })
          .catch((error) => {
              console.error(error);
          });    
      }

每当我在搜索框中输入内容时,如何使用搜索功能更新我的列表?

这就是我在 TextInput (SearchBox) 中尝试的。

<TextInput style={styles.searchInput} 
 placeholder="Search"
 placeholderTextColor= {colors.whiteColor}
 onChangeText={ 
 name => { 
 this.setState({name}); 
 this.search(); 
}
 }
 />

标签: androidjsonreactjsreact-native

解决方案


首先responseJson是一个实际的 json 对象,您不需要对其进行字符串化然后解析它。

您可以将 responseJson 存储在状态中

search = () => {
      fetch(strings.baseUri+"search_by_name", {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ 
          "name": this.state.name,
        })
      })
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({data: responseJson});    
     })
      .catch((error) => {
          console.error(error);
      });    
  }

只需确保在组件的构造函数中设置初始状态

constructor(props) {
  super(props);
  this.state = { data: [] }
}

然后你应该能够通过使用访问你的数据this.state.data

更新问题的更新答案

问题是您没有意识到 setState 是异步的。那就是状态更新需要时间。这意味着您正在设置状态,然后希望在调用下一个函数时状态已经更新。不幸的是,在 TextInput 中调用 setState 并没有达到预期的效果。

我会将您的搜索功能更新为以下内容

search = (name) => {
      fetch(strings.baseUri+"search_by_name", {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ 
          "name": name,
        })
      })
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({data: responseJson, name: name});    
     })
      .catch((error) => {
          this.setState({name: name});
          console.error(error);
      });    
  }

然后在你TextInput更新你的函数调用

<TextInput style={styles.searchInput} 
 placeholder="Search"
 placeholderTextColor={colors.whiteColor}
 onChangeText={ name => { 
   if (name.length > 0) {
    this.search(name); 
   } else {
    this.setState({data: [], name: ''});
   }
  }
 }
/>

这将减少调用 setState 的次数。


推荐阅读