简体   繁体   English

在反应 redux 中使用空值搜索返回空数组而不是整个数据

[英]Searching with empty value returning empty array instead of entire data in react redux

I am creating a crud web app where I have rendered all the users into the table coming from third party API.我正在创建一个 crud web 应用程序,我已将所有用户呈现到来自第三方 API 的表中。 Now, I am implementing a simple search box to filter table data according to First Name .现在,我正在实现一个简单的搜索框来根据First Name过滤表数据。 But when I start typing and write first letter, It filters out the result but when I press backspace means empty the search box, It's returning me an empty array instead of providing me the entire data.但是当我开始输入并写第一个字母时,它会过滤掉结果,但是当我按下退格键意味着清空搜索框时,它会返回一个空数组而不是为我提供整个数据。

Below is my react redux code for the same:下面是我的反应 redux 代码:

Component零件

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);

Action行动

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};
}

Reducer减速器

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;

I have removed extra code & made it extremely easy to understand.我删除了额外的代码并使其非常容易理解。 Please help me guys to know where I am stucked.请帮助我的人知道我被困在哪里。

This is happening because you are updating users array with empty array when some results to empty array.发生这种情况是因为当某些结果为空数组时,您正在使用空数组更新用户数组。

1.Store api response in users array. 1.将 api 响应存储在 users 数组中。 also in filtered array 2.on search keep updating filtered array but filter on users array 3. Render filtered array and not users array也在过滤数组 2.on 搜索不断更新过滤数组但过滤用户数组 3. 渲染过滤数组而不是用户数组

onChange={(e) => this.props.searchAction(e.target.value)}

THIS LINE IS THE PROBLEM这条线是问题

First, you need to handle the change (change the state), then you need to do the action based on that state.首先,您需要处理更改(更改状态),然后您需要根据该 state 执行操作。 When you call the action immediately, then you get the empty string ' '.当您立即调用该操作时,您将获得空字符串“”。

Here is an implementation I did using Hooks:这是我使用 Hooks 完成的一个实现:

let { handleSearch } = props;
const [query, setQuery] = useState("");
const handleChange = e => {
setQuery(e.target.value);
};
useEffect(() => {
handleSearch(query);
}, [query]);
return (
<>
<div className="TableHeader-search">
<InputGroupAddon addonType="prepend">
<InputGroupText className="TableHeader-search__icon">
<img src={mGlass} alt="search" />
</InputGroupText>
</InputGroupAddon>
<input
className="TableHeader-search__input"
type="text"
onChange={handleChange}
placeholder={"Search..."}
name="search"
value={query}
/>
</div>
</>
);
};

Notice the onChange action does the handleChange function first... Good Luck.请注意 onChange 操作首先执行 handleChange function ......祝你好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM