React类组件路由params参数变化时无法重新渲染问题求解
问题根因
componentDidUpdate生命周期的入参顺序错误,正确入参顺序为componentDidUpdate(prevProps, prevState),你当前写法里第一个参数实际拿到的是上一轮的props,判断逻辑完全不符合预期。- 你在
componentDidUpdate中只要检测到type不等就直接调用setState,而setState本身会触发组件更新、再次执行componentDidUpdate,判断条件持续成立时就会进入无限更新循环,触发深度超限报错。 - 路由参数变化后你没有重新调用拉取数据的方法,所以页面内容不会同步更新。
修复代码
// 改为类属性箭头函数,避免this指向问题 getItems = () => { client .query({ query: GET_ITEMS, }) .then((result) => this.setState({ items: result.data.items }) ); }; componentDidMount() { const { type } = this.props.match.params; this.setState({ type }); this.getItems(); } // 调整入参顺序,只对比上一轮的路由参数 componentDidUpdate(prevProps) { const currType = this.props.match.params.type; const prevType = prevProps.match.params.type; if (currType !== prevType) { this.setState({ type: currType }); // 路由参数变化后重新拉取对应数据 this.getItems(); } } render() { const { type, items } = this.state; return ( <ul className={stl.list}> {/* 循环元素添加唯一key,避免react警告 */} {items?.map(({ name }) => ( <div key={name}> <li style={type === name ? activeTabStyle : {}} onClick={() => this.handleTabClick(name)} > {name} </li> {type === name && <div className={stl.underline}></div>} </div> ))} </ul> ); }
内容的提问来源于stack exchange,提问作者Davrick
相关产品推荐
相关产品推荐

