简体   繁体   中英

How to Implement Price Increase and Decrease Sorting in React Redux Application?

Friends, all the good time of the day, you need to implement the sorting of goods by increasing and decreasing prices. How to write such an action.? I tried in action to write a sorting of an array of objects using the sort method. The array itself is created in the store using the React hook UseEffect as the second parameter in UseEffect, I passed this same array, but redrawing occurs only when we go to the basket and in real time we do not see redrawing. Tell me what I'm doing wrong? Here is the component itself that loads products into the store and renders them:

function Home() {
    const books = useSelector(state=>state.books.books);
    const isFetched = useSelector(state=>state.books.isFetched);
    const dispatch = useDispatch();

    useEffect(()=>{
      if(!books.length ){
        dispatch(setBooks())
      } 
    },[books]
);
    

    return (
       
      <Card.Group itemsPerRow={5}>
                {!isFetched ?  <Loader/> : books.map(i=>(<Books title = {i.title}
                 key={i.id}
                 author={i.author} 
                 image={i.image} 
                 price={i.price}
                 rating={i.rating}
                 />))}
        </Card.Group>
    );
}

And here is the reducer in which the sorting and the link for loading goods into the store are written:

const initialState = {
    books: [],
    isFetched: false,
}

export const SET_BOOKS = 'SET_BOOKS';


export const setBooks = (books) =>{
    return async dispatch => {
        const response = await fetch('http://localhost:3000/books');
        const json = await response.json();
        dispatch({
            type: SET_BOOKS,
            payload: json
        });
    }
 }
  
 const SET_FILTER_LOWER = 'SET_FILTER_LOWER';

 export const setFilter = filter => ({
   type: SET_FILTER_LOWER,
   payload: filter,
 });

 export const setBooksReducer = (state = initialState, action) =>{
     switch(action.type){
        case SET_BOOKS:
            return {...state, 
                books: state.books.concat(action.payload),
                isFetched: true
            }
        case SET_FILTER_LOWER:
        return {
          ...state,
          books: action.payload.sort((a,b)=>a.price-b.price)
        //   books: action.payload.filter((el)=>el.price<=300)
        };
        default: 
        return state

     }
      
}

Filtering component:

const MenuFilter = () => {
    const dispatch = useDispatch();
    const books = useSelector(state=>state.books.books);
    return (
        <div className="menu_filter">
        <Menu pointing>
          <Menu.Item
            name='Дороже'
          />
          <Menu.Item
            name='Дешевле'
            onClick={()=>dispatch(setFilter(books))}
            
          />
        </Menu>

      </div>
    );
}

export default MenuFilter;

Lets say your selector of books gives you an unsorted array of prices, right?

[
 {price: 0.99},
 {price: 1.22},
 {price: 0.49},
 {price: 0.22}
]

Now, instead of using books directly you could create a const that has a sorted version of that.

const newBooks = [...books];

And then sort it there.

newBooks.sort((book1, book2) => book1.price - book2.price))

And now you can map newBooks.

newBooks.map(i=>(<Books title = {i.title}
                 key={i.id}
                 author={i.author} 
                 image={i.image} 
                 price={i.price}
                 rating={i.rating}
                 />))

I do not recommend sorting it directly from books, as that would give you some unexpected behavior or updates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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