最近在写项目的时候发现有的时候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属性了

Logo

快速构建 Web 应用程序

更多推荐