React-router中解决match, location和history属性找不到的问题(React项目开发过程中遇到的问题总结)
从19年6月份毕业,参加工作快两个月了,之前在学校的时候也有过将近一年半的时间都在实习,说是实习因为没毕业的原因,签不了劳务合同(说白了签不了卖身契,哈哈哈!!!)。现在参加正式签合同了,感觉仪式感满满的。现在公司在做一个可配置化的调度管理系统,虽然说之前也有做过管理系统,但大部分路由,和页面都是写死的。现在要做全部的可配置化·,逻辑复杂程度上比之前的要高出好几个层次(之前写的管理系统传在了自己.
·
最近在写项目的时候发现有的时候match, location和history三个属性在一些组件中总找不到,于是翻看了几遍文档。
这里做一下总结
class Text extends React.Component {
//这是第一个组件
}
class Texttwo extends React.Component {
render(){
return(
<Text />
)
}
//这是第二个组件
}
上述代码我们分别创建了Text 和Texttwo组件,Texttwo中引用了text
但我们在使用路由时
只将Texttwo注入到了component={Texttwo}中,此时Texttwo为路由组件,而Text并不是路由组件只是被引用的普通组件,所以它访问不到match, location和history三个属性。
所以这里就需要将Text包装成路由组件。
react-router提供了withRouter方法,我们需要在封装Text组件的文件中将其解构出来
import { withRouter } from "react-router-dom";
此时再在文件最后将组件包装成路由组件,并且默认导出就好了
export default withRouter(Text)
这时Text组件就有match, location和history属性了
更多推荐
已为社区贡献1条内容
所有评论(0)