reactjs - 如何从待办事项列表中过滤数据
问题描述
我是redux的新手,我想在待办事项列表上显示过滤数据,如果我搜索任何关键字它的显示和其他数据将被隐藏,我该怎么办,请帮忙。
这是我的 todo.js 文件,我在其中获取所有待办事项数据。
import React, { useState } from 'react';
import { useSelector } from 'react-redux'
const Todo = () => {
const todos = useSelector((state) => state.todos);
console.log(todos);
const [search, setSearch] = useState("");
return (
<div className="container">
<div className="form-group">
<input type="text"
className="form-control"
id="exampleFormControlInput1"
placeholder="Search Todo..."
value={search}
onChange={(e) => setSearch(e.target.value)} />
</div>
<table className="table shadow" >
<thead>
<tr className="bg-danger text-white">
<th scope="col">Todo Id</th>
<th scope="col">Title</th>
<th scope="col">Status</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
{
todos.map(todo => {
return (
<tr>
<th scope="row">{todo.id}</th>
<td>{todo.title}</td>
<td>Complete</td>
<td><button className="btn btn-primary">View User</button></td>
</tr>
)
})
}
</tbody>
</table>
</div>
)
}
export default Todo;
这是我初始化所有待办事项并执行一些搜索操作的 store.js 文件
import { createStore } from 'redux';
import {SEARCH_TODO} from './Action/action';
const initialState = {
todos: [
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
},
{
"userId": 1,
"id": 3,
"title": "fugiat veniam minus",
"completed": false
},
{
"userId": 1,
"id": 4,
"title": "et porro tempora",
"completed": true
},
{
"userId": 1,
"id": 5,
"title": "laboriosam mollitia et enim quasi adipisci quia provident illum",
"completed": false
}
]
}
const todoReducer = (state = initialState, action) => {
switch (action.type) {
case SEARCH_TODO:
return Object.assign({}, state, {
todos: action.title
})
default:
return state;
}
}
const store = createStore(todoReducer);
export default store;
这是我的 App.js 文件。
import React from 'react';
import './App.css';
import Todo from './components/Todo';
import { Provider } from 'react-redux';
import store from './store';
function App() {
return (
<Provider store={store}>
<div className="App">
<h1>Todo fetch from json</h1>
<Todo />
</div>
</Provider>
)
}
export default App;
解决方案
如果您根本不需要将其存储在 Redux 状态中,您可以在此之前使用过滤器功能,而不是只立即映射待办事项。
todos.filter(todo => todo.title.startsWith(search)).map(todo => {
return (
...
)
})
此代码假定您要根据 startsWith 函数进行搜索,但当然也有您可能希望用于搜索的条件。请记住,首先将搜索和标题小写可能很有用,以确保即使有人将文本大写,它仍然可以找到标题。
推荐阅读
- r - R 在组中拆分以进行并行执行
- shiny - selectInput R Shiny中的动态组数
- c# - 通过 Unity3D 创建 OPC UA 客户端
- c# - Wix 安装程序 - 在升级时保留应用程序池用户
- java - 在 Java 中使用冒泡排序按字母顺序对名称数组进行排序
- python - Python Json.load 上的错误:额外数据行 10 第 2 列(字符 194)
- php - PHP:Check is null 作为参数传递或分配为默认值
- google-apis-explorer - 如何使用 youtube api 获取具有多个 videocategoryid 的视频
- mysql - MySQL SELECT 其他表中不存在的行的子字符串
- java - 无法从 Java 服务器向 android 设备发送 firebase fcm 推送通知