首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >搜索使用异步存储存储的项

搜索使用异步存储存储的项
EN

Stack Overflow用户
提问于 2020-07-13 10:27:07
回答 1查看 424关注 0票数 0

我有一个使用异步存储存储的平面列表(卡片)中显示的项目列表,我想使用搜索栏进行搜索,我从这里获得项的数据(存储在异步存储中)。状态。保存的,如您在下面的代码中所看到的

因为某种原因,我的方法不起作用,我也不明白为什么?我对长代码表示歉意,任何帮助都将不胜感激。

代码语言:javascript
复制
class SaveSearchList extends Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: false,
      data: [],
      temp: [],
      error: null,
      search: null,
      saved: [],
    };
  }
  removeItem = () => {
    DeleteItem("saved")
      .then((res) => {
        this.setState({
          saved: [],
        });
        console.log(res);
      })
      .catch((e) => console.log(e));
  };
  componentDidMount = () => {
    this.getData();
    this.readItems();
    this.unsubscribe = this.props.navigation.addListener(
      "focus",
      this.readItems
    );
  };
  componentWillUnmount() {
    this.unsubscribe();
  }
  readItems = () => {
    ReadItem("saved")
      .then((res) => {
        if (res) {
          const saved = JSON.parse(res);
          this.setState({
            saved: saved,
          });
        }
      })
      .catch((e) => console.warn(e));
  };
  getData = async () => {
    this.setState({ loading: true });

    try {
      this.setResult(this.state.saved);
    } catch (e) {
      this.setState({ error: "Error Loading content", loading: false });
    }
  };
  setResult = (res) => {
    this.setState({
      data: [...this.state.data, ...res],
      temp: [...this.state.temp, ...res],
      error: res.error || null,
      loading: false,
    });
  };

  renderHeader = () => {
    return (
      <View style={{}}>
        <Text
          style={{
            color: colors.shade2,
            fontSize: 30,
            fontWeight: "bold",
            textAlign: "center",
          }}
        >
          Browse Saved Articles
        </Text>
        <SearchBar
          containerStyle={{
            borderWidth: 1,
            borderRadius: 5,
            borderColor: "#353540",
            borderTopColor: "#353540",
            borderBottomColor: "#353540",
          }}
          inputContainerStyle={{ backgroundColor: colors.shade1 }}
          round
          showLoading
          placeholder="Search for articles"
          onChangeText={this.updateSearch}
          value={this.state.search}
        />
      </View>
    );
  };

  updateSearch = (search) => {
    this.setState({ search }, () => {
      if ("" == search) {
        this.setState({
          data: [...this.state.temp],
        });
        return;
      }

      this.state.data = this.state.temp
        .filter(function (item) {
          return item.title.includes(search);
        })
        .map(function ({ id, title, category, img, content }) {
          return { id, title, category, img, content };
        });
    });
  };

  render() {
    return this.state.error != null ? (
      <View
        style={{
          flex: 1,
          flexDirection: "column",
          justifyContent: "center",
          alignItems: "center",
        }}
      >
        <Text>{this.state.error}</Text>
        <Button
          onPress={() => {
            console.log("nothing");
          }}
          title="Reload"
        />
      </View>
    ) : (
      <View style={{ top: 50 }}>
        <FlatList
          style={{}}
          ListHeaderComponent={this.renderHeader}
          data={this.state.saved}
          keyExtractor={(item) => item._id}
          renderItem={({ item }) => {
            return (
              <TouchableScale
                activeScale={0.9}
                tension={50}
                friction={7}
                useNativeDriver
                onPress={() =>
                  this.props.navigation.navigate("DetailScreen", {
                    data: item,
                  })
                }
              >
                <View style={{ left: 10, top: 20 }}>
                  <Card item={item} />
                </View>
              </TouchableScale>
            );
          }}
        />
        <View style={styles.button}>
          {this.state.saved.length > 0 && (
            <AppButton
              title="Remove Key"
              color="secondary"
              onPress={this.removeItem}
            />
          )}
        </View>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  button: {
    top: 20,
    width: 300,
    height: 250,
    alignItems: "center",
    left: 40,
  },
});
export default SaveSearchList;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-13 12:34:38

如果我让您正确,您正在加载所有已保存的项目,然后您希望使用搜索文本筛选它们(只有与搜索相关的项目才会出现)。

问题是,更改搜索栏文本更改了"this.state.data“,而平面列表数据更改为"this.state.saved",搜索文本更改后不会更改。

更清楚的是,我正在添加我认为应该更改的代码。

电流:

代码语言:javascript
复制
updateSearch = (search) => {
    this.setState({ search }, () => {
      if ("" == search) {
        this.setState({
          data: [...this.state.temp],
        });
        return;
      }

      this.state.data = this.state.temp
        .filter(function (item) {
          return item.title.includes(search);
        })
        .map(function ({ id, title, category, img, content }) {
          return { id, title, category, img, content };
        });
    });
  };

代码语言:javascript
复制
...
...
  <FlatList
      style={{}}
      ListHeaderComponent={this.renderHeader}
      data={this.state.saved}
      keyExtractor={(item) => item._id}
      renderItem={({ item }) => {
        return (
          <TouchableScale
            activeScale={0.9}
            tension={50}
            friction={7}
 ...
 ...

改为:

代码语言:javascript
复制
updateSearch = (search) => {
    this.setState({ search }, () => {
      if ("" == search) {
        this.setState({
          data: [...this.state.temp],
        });
        return;
      }

      this.setState({ data: this.state.temp
        .filter(function (item) {
          return item.title.includes(search);
        })
        .map(function ({ id, title, category, img, content }) {
          return { id, title, category, img, content };
        });
    });
  };

代码语言:javascript
复制
...
...
  <FlatList
      style={{}}
      ListHeaderComponent={this.renderHeader}
      data={this.state.data}                   <------------- CHANGED --------
      keyExtractor={(item) => item._id}
      renderItem={({ item }) => {
        return (
          <TouchableScale
            activeScale={0.9}
            tension={50}
            friction={7}
 ...
 ...

代码语言:javascript
复制
readItems = () => {
    ReadItem("saved")
      .then((res) => {
        if (res) {
          const saved = JSON.parse(res);
          this.setState({
            saved: saved, temp: saved, data: saved          //  <---------- CHANGED ----
          });
        }
      })
      .catch((e) => console.warn(e));
  };
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62873897

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档