React类组件状态提升失败,是结构设计问题还是有遗漏的解决方案?
解决方案
你可以通过以下两类类组件兼容的方案获取路由传递的quote值,全程无需在业务代码中引入Hook:
方案1:使用官方withRouter高阶组件(适配react-router v5及更低版本)
withRouter是react-router官方提供的高阶组件,可直接将路由相关属性注入到类组件的props中。
操作步骤:
- 导入依赖
import { withRouter } from 'react-router-dom';
- 改造
Shirtselect组件导出逻辑
class Shirtselect extends React.Component { // 组件任意生命周期/方法中都可以直接取到传递的quote componentDidMount() { const targetQuote = this.props.location.state?.quote; // 后续业务逻辑 } // 其他原有组件代码... } // 导出时用withRouter包裹即可 export default withRouter(Shirtselect);
方案2:自定义高阶组件(适配react-router v6版本)
react-router v6移除了官方的withRouter,你可以自行封装一个高阶组件实现相同能力,该高阶组件内部使用的Hook仅作为封装工具,不会侵入你的业务代码,你编写的Shirtselect依然是纯类组件实现,符合你的技术要求。
操作步骤:
- 封装自定义
withRouter工具
import { useLocation, useNavigate, useParams } from 'react-router-dom'; const withRouter = (Component) => { const Wrapper = (props) => { const location = useLocation(); const navigate = useNavigate(); const params = useParams(); return <Component {...props} location={location} navigate={navigate} params={params} />; }; return Wrapper; };
- 和方案1相同,用自定义的
withRouter包裹Shirtselect组件导出,即可通过this.props.location.state.quote拿到传递的文案值。
可选替代方案:公开参数传递
如果你不想使用路由隐式state传递,也可以将quote序列化后放在路由查询参数/路径参数中传递:
- 修改路由配置(以路径参数为例)
<Route exact path='/shirtselect/:quote' render={() => <Shirtselect/>}/>
- 调整
LinkContainer跳转路径
<LinkContainer to={`/shirtselect/${encodeURIComponent(this.props.quote)}`}> {/* 原有按钮代码 */} </LinkContainer>
- 同样通过
withRouter拿到props.params.quote,解码后即可使用。
内容的提问来源于stack exchange,提问作者user15170
相关产品推荐
相关产品推荐

