You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React对接Django时如何通过API传递筛选关键词实现分类过滤功能

问题修复方案

你代码的核心问题是前端请求参数传递方式和Django接口的接收逻辑不匹配,同时分类页没有正确读取路由查询参数触发请求,按以下步骤修改即可:

1. 修正分类查询Action的请求逻辑

Django接口从查询参数中读取keyword1,不要把参数拼在请求路径末尾,修改为通过axios的params配置项传递:

export const categoryListProducts = (keyword1 = '') => async (dispatch) => {
    try {
        dispatch({ type: PRODUCT_CATEGORY_LIST_REQUEST })
        // 修正请求路径和参数传递方式
        const { data } = await axios.get(`/api/products/category/`,{
            params: {
                keyword1: keyword1
            }
        })
        dispatch({
            type: PRODUCT_CATEGORY_LIST_SUCCESS,
            payload: data
        })
    }catch(error){
        dispatch({
            type: PRODUCT_CATEGORY_LIST_FAIL,
            payload: error.response && error.response.data.detail
            ? error.response.data.detail
            : error.message,
        })
    }
}

2. 修正分类页的参数读取和请求逻辑

  • 从路由中读取查询参数keyword1传给请求方法
  • 修正useSelector取值,对应你定义的分类列表reducer
  • 把keyword1加入useEffect依赖,参数变化自动重新请求
// 除了history还要接收location参数,用来读取查询参数
function CategoryScreen({history, location}) {
    const dispatch = useDispatch()
    // 修正:取分类列表的reducer,这里要和你store里注册的reducer key保持一致
    const categoryProductList = useSelector(state => state.categoryProductList)
    const {error, loading, products} = categoryProductList

    useEffect(() => {
        // 读取URL查询参数中的keyword1
        const searchParams = new URLSearchParams(location.search)
        const keyword1 = searchParams.get('keyword1') || ''
        // 传递参数调用请求方法
        dispatch(categoryListProducts(keyword1))
    }, [dispatch, location.search]) // 把location.search加入依赖


    return (
        <div>
            {loading ? <Loader />
                : error ? <Message variant='danger'>{error}</Message>
                    :
                    <Row className='flex flex-wrap' >

                            {products.map(product => (
                                <Col key={product._id} sm={12} md={6} lg={4} xl={3}>
                                    <Product product={product} />
                                </Col>
                            ))}
                    </Row>  
            } 
        </div>
    )
}

export default CategoryScreen

3. 实现点击按钮跳转带筛选参数的链接

两种实现方式选其一即可:

方式1:使用React Router的Link组件

import { Link } from 'react-router-dom'

// 按钮示例
<Link to="/category/?keyword1=1">
    <Button>筛选分类1商品</Button>
</Link>

方式2:使用history.push跳转

// 在组件内获取history对象后调用
<Button onClick={() => history.push('/category/?keyword1=1')}>
    筛选分类1商品
</Button>

4. 路由配置无需修改

你现有的路由配置<Route path='/category' component={CategoryScreen} />已经可以支持带查询参数的访问,不需要调整。

内容的提问来源于stack exchange,提问作者Sohanur Rahman Shanto 16209570

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 00:30:03