企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[toc] ## old ### 使用 父容器 ``` export default class xxx extends React.Component{ static childContextTypes = { location:PropTypes.object ,history:PropTypes.object } getChildContext(){ let that = this; return { location:this.state.location ,history:{ push(path){ if(typeof path == 'object'){ // state 是用来保存状态的 let {pathname,state} = path; that.setState({location:{...that.state.location,state}},()=>{ window.location.hash = pathname; }) }else{ window.location.hash = path; //会自动添加'#' } } } } } ``` 子孙 ``` static contextTypes = { location: PropTypes.object , history: PropTypes.object } ... this.context -> 指向的即是 contextTypes声明的对象 ... ``` ### 注意事项 ``` getChildContext(){ return { location:this.state.location ,history:(hash)=>{ window.location.hash = hash; } } } <<< index.js:2178 Warning: Failed child context type: Invalid child context `history` of type `function` supplied to `xxx`, expected `object`. in xxx (at App.js:11) ``` return的必须是一个对象,且这个对象里的属性的值也必须是对象,否则就会像上栗一样报错 ``` getChildContext(){ return { location:this.state.location ,history:{ push:(hash)=>window.location.hash = hash } } } ```