我是redux的新手,我想在todo列表上显示过滤数据,如果我在任何关键字上搜索它的显示和其他数据都会被隐藏,我该怎么做,请帮助。
这是我获取所有todo数据的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文件,我在其中初始化我的所有todo,并尽可能执行一些搜索操作
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状态下,您可以在此之前使用filter函数,而不是仅立即映射todos。
todos.filter(todo => todo.title.startsWith(search)).map(todo => {
return (
...
)
})
这段代码假设您希望基于startsWith函数进行搜索,但当然也有一些搜索条件。请记住,首先将搜索和标题小写可能很有用,以确保即使有人将文本大写,它仍然能找到标题。