我正在创建一个Crud Web应用程序,在该应用程序中,我已将所有用户呈现给来自第三方API的表。现在,我正在实现一个简单的搜索框,以根据名字过滤表数据。但是,当我开始键入并写出第一个字母时,它会过滤出结果,但是当我按退格键时,意味着会清空搜索框,它将返回一个空数组,而不是向我提供全部数据。
下面是我的相同的redux代码:
零件
import React from 'react';
import {connect} from 'react-redux'
import {fetchAllUsersAction,searchByUserName} from '../../redux/actions/user';
const mapStateToProps = (state) =>{
return{
users: state.usersData.users
}
}
const mapDispatchToProps = (dispatch,props) =>{
return{
fetchUsersAction: (pageNumber) => {dispatch(fetchAllUsersAction(pageNumber))},
searchAction: (value)=>{dispatch(searchByUserName(value))}
}
}
class Users extends React.Component{
render(){
let {users} = this.props;
return(
<React.Fragment>
<div className="container">
<div className="row mt-5">
<button className="btn btn-secondary" onClick={()=>this.props.fetchUsersAction(1)}>Fetch Users Data</button>
<input type="text" className="form-control" placeholder="Search with user name..." onChange={(e) => this.props.searchAction(e.target.value)} />
</div>
<div className="row mt-5 table-responsive">
<table className="table table-hover table-bordered">
<thead>
<tr>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">Email</th>
</tr>
</thead>
<tbody>
(users.length>0)?
users.map((item,index)=>(
<tr key={item.id}>
<td>{item.first_name}</td>
<td>{item.last_name}</td>
<td>{item.email}</td>
</tr>
))
:
<tr>
<td colSpan="7">No users found!</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</React.Fragment>
);
}
}
export default connect(mapStateToProps,mapDispatchToProps)(Users);
行动
import {
FETCH_ALL_USERS_SUCCESS,
SEARCH_BY_USER_NAME
} from './action-types';
function fetchAllUsersSuccess(usersData){
return {
type: FETCH_ALL_USERS_SUCCESS,
users_data: usersData
}
}
export function fetchAllUsersAction(pageNumber) {
return function(dispatch){
fetch('https://reqres.in/api/users?page='+pageNumber)
.then(res=>res.json())
.then(json=>{
dispatch(fetchAllUsersSuccess(json));
})
}
}
export function searchByUserName(value){
return {type: SEARCH_BY_USER_NAME, value};
}
减速器
import {
FETCH_ALL_USERS_SUCCESS,
SEARCH_BY_USER_NAME
} from '../actions/action-types';
const initialState = {
users: []
}
const userReducer = function(state = initialState, action) {
switch(action.type) {
case FETCH_ALL_USERS_SUCCESS:
return {
...state,
users: action.users_data.data
}
case SEARCH_BY_USER_NAME: {
const {value} = action;
const filtered_users = state.users.filter((val) => val.first_name.includes(value));
return {...state, users:filtered_users};
}
default:
return state;
}
}
export default userReducer;
我删除了多余的代码,并使其非常易于理解。请帮助我了解我的位置。