如何在 React js 中使用获取的数据过滤数组?

奥莉安娜·阿布雷乌

我试图通过在输入中输入用户号来过滤获取的博客文章。此数字应与帖子 userId 匹配并仅显示该给定用户“撰写”的帖子(这是一个从 1 到 10 的数字,每个用户有 10 个帖子)。

问题:当我在输入中输入一个数字时,帖子会消失并且不会过滤任何内容。我很确定我坚持使用过滤器功能。

提前致谢!

function App(pst) {

  const [posts, setPosts] = useState([]);
  const [query, setQuery] = useState('');

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts/')
      .then(response => response.json())
      .then(json => setPosts(json))
  }, [])

  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      
      <Router>
          <NavBar />
          <Switch>
            <Route exact path='/'>
              <Home />
              <SearchBar 
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              />
              <Grid container spacing={2} justify='center'>
                {posts.filter((val) => {
                  if (query === '') {
                    return val
                  } else if (query === val.userId) {
                    return val
                  }
                  console.log(query);
                }).map((pst) => (
                  <PostCard pst={pst} key={pst.id}/>
                ))}
              </Grid>
            </Route>
            <Route exact path='/singlePost/:postId' component={SinglePost} />
            <Route exact path='/PostList'>
              <PostList pst={pst}/>
            </Route>
          </Switch>
      </Router>
    </ ThemeProvider>
  );
}
马特·卡洛塔

过滤数据有两种主要方式:客户端或服务器端。有时,在处理大型数据集和复杂数据结构时,服务器端的性能会更高。在您的示例中,数据非常小,数据结构非常扁平,因此客户端过滤就足够了。

首先是第一件事,因为您希望过滤所有呈现给客户端的数据,所以您需要将该数据存储到其自己的posts状态。然后,您将拥有某种searchValue状态,每当用户更改input时,该状态就会发生变化利用这两种状态,您可以过滤postswithsearchValue并将结果存储到其自己的filteredPosts状态。

React 只会在stateprops更改时重新渲染组件因此,您需要利用状态更改来使您的组件保持最新状态。

工作演示

编辑过滤器数据

代码

应用程序.js

import * as React from "react";
import "./styles.css";

export default function App() {
  const [searchValue, setSearch] = React.useState(0);
  const [posts, setPosts] = React.useState([]);
  const [filteredPosts, setFilteredPosts] = React.useState([]);

  const handleSearchChange = (event) => {
    /*
      This "handleSearchChange" is a callback function that accepts an
      "event" as an argument. 

      This "event" contains the "input" DOM element. And this
      element contains a "value" property that is stored as 
      a string on the "target" property. This "event.target.value"
      will update the input's "searchValue" state.

      Please note, "event.target.value" will be a string and when
      filtering the post's "id", which is a number, a string value of "1" 
      won't equal a post id of number 1! Therefore, parseInt(string, 10)
      coverts the string value to a number value.
    */
    setSearch(parseInt(event.target.value, 10));
  };

  const handleSearchReset = () => {
    setSearch(0);
  };

  React.useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then((response) => response.json())
      .then((json) => setPosts(json));
  }, []);

  React.useEffect(() => {
    /*
      When the searchValue changes, filter the posts by id with
      searchValue and store the result to "filteredPosts"
    */
    setFilteredPosts(posts.filter((post) => post.id === searchValue));
  }, [posts, searchValue]);

  return (
    <div className="App">
      <h1>Search Posts</h1>
      <input
        min={0}
        value={searchValue}
        type="number"
        onChange={handleSearchChange}
      />
      <br />
      <button type="button" onClick={handleSearchReset}>
        Reset Search
      </button>
      <h1>Filtered Posts</h1>
      <pre className="code">
        <code>{JSON.stringify(filteredPosts, null, 2)}</code>
      </pre>
      <h1>Available Posts</h1>
      <pre className="code">
        <code>{JSON.stringify(posts, null, 2)}</code>
      </pre>
    </div>
  );
}

索引.js

import * as React from "react";
import ReactDOM from "react-dom";
import App from "./App";

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在React.js中使用获取的数据过滤数组?

如何在 REACT JS 中使用过滤器映射图像数组

如何从javascript数组对象/JSON获取数据并在React JS中使用它

如何在React JS中使用路由从查询字符串中获取数据

如何在React中使用ALERTIFY JS?

如何在 React js 中使用 forEach

从React中的API过滤数组数据时,如何在表单提交中使用startsWith?

如何在React Native中使用immutable.js和redux-actions从firestore中获取数据?

如何在React js中插入数据

如何在React js中使用数组将对象推入数组?

在使用useContext在React.js中进行过滤后如何重新获取数据

如何在 Chart JS 数据集中使用数据数组?

如何在react js中显示数组数据?

如何在 React JS 中将数据作为对象数组插入

如何在React.js中使用字符串数组使用变量名

如何使用数据范围过滤 json 数据(React JS)

如何在React Native中使用数组映射JSON数据

如何在React组件中使用数组映射JSON数据

如何在 React.js 中使用这个 Javascript 动画

如何在 React JS 中使用 Google Fonts API?

如何在React JS中使用条件运算符

如何在video.js中使用React Hooks?

如何在React js中使用Fine Uploader

如何在React-Native中使用leaflet.js

如何在React JS中使用道具传递内联样式?

如何在 React JS 中使用 onSubmit 更改 DOM?

如何在AdonisJs中使用React.js

如何在React JS中使用jQuery UI

如何在 React JS 渲染方法中使用变量?