React中点击颜色、尺寸筛选条件时触发GET请求拉取数据的实现方法
你的实现思路是正确的,使用componentDidUpdate监听路由变化触发数据拉取,刚好匹配你点击筛选后通过history.push更新路由的逻辑,之前的代码不生效是因为判断条件仅校验了match.params.name,没有覆盖查询参数(color、size)的变更。
具体修改方案如下:
- 补全state的初始声明
你在updateSize中用到了selectedItemSize,但constructor中没有声明该字段,需要补全避免运行警告:
constructor(props) { super(props); this.state = { productsInfo: [], selectedItemColor: [], selectedItemSize: [] // 新增缺失的初始字段 }; }
- 抽离公共数据拉取方法,同时调整生命周期逻辑
把数据拉取逻辑抽为公共方法,在componentDidMount和componentDidUpdate中复用,同时调整比对条件,只要路由路径或者查询参数发生变化,就触发数据拉取,同时同步选中的筛选状态到state,保证视图和路由一致,刷新页面也能保留选中状态:
componentDidMount() { // 首次加载根据当前路由拉取对应数据 this.fetchProducts(); } componentDidUpdate(prevProps) { // 仅当路径或查询参数变化时才触发更新,避免无限循环 if ( prevProps.location.pathname !== this.props.location.pathname || prevProps.location.search !== this.props.location.search ) { this.fetchProducts(); // 同步路由中的筛选值到state const urlParams = new URLSearchParams(this.props.location.search); this.setState({ selectedItemColor: urlParams.getAll('color'), selectedItemSize: urlParams.getAll('size') }) } } // 抽离公共拉取方法,无需手动拼接color、size参数,直接复用路由中已处理好的查询字符串 fetchProducts = () => { const { pathname, search } = this.props.location; fetch(`${API}${pathname}${search}`) .then(res => res.json()) .then(data => { this.setState({ productsInfo: data, }); }); }
- 冗余逻辑清理
updateSize和updateColor方法中原来手动设置selectedItemSize、selectedItemColor的代码可以删除,已经通过componentDidUpdate自动同步,逻辑更统一。原来分类按钮的updateProducts方法也可以删除,点击分类修改路由路径后会自动触发fetchProducts拉取对应分类的数据。
内容的提问来源于stack exchange,提问作者JiwanJeon94
相关产品推荐
相关产品推荐

