栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

除了实例的属性可以获取Context外哪些地方还能直接获取Context呢?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

除了实例的属性可以获取Context外哪些地方还能直接获取Context呢?

构造函数 constructor(props,context)
生命周期 componentWillReceiveProps(nextProps,nextContext)
shouldComponentUpdate(nextProps,nextState,nextContext)
componentWillUpdate(nextProps,nextState,nextContext)

通过上面方法测试,没获取到

<!DOCTYPE html><html><head>    <meta charset="utf-8" />    <title>react demo</title>    <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>    <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script></head><body><div id="app"></div><script type="text/babel">        const { createContext } = React;    //创建store    const AppContext=createContext({});    class A  extends React.Component{        constructor(props,context){ super(props); this.state={     a:context }        }        shouldComponentUpdate(nextProps, nextState,nextContext) { console.log(nextContext); return true;        }        componentDidMount() { console.log(this.state.a.name);        }        //从store中取值        render(){ return (     <AppContext.Consumer>         {  (context)=>{      return  <div>          <div>A组件Name:{context.name}</div>          <button onClick={context.changeName}>改变name</button>      </div>  }         }     </AppContext.Consumer> )        }    }    class App extends React.Component{        //在顶层包裹所有元素,注入到每个子组件中        constructor(props){ super(props); this.state={     name:'xz' }        }        shouldComponentUpdate(nextProps, nextState,nextContext) { console.log(nextContext,11); return true;        }        render(){ return (     <AppContext.Provider value={{name:this.state.name,changeName:()=>{  this.setState({      name:Math.random()  })         }}}>         <A/>     </AppContext.Provider> )        }    }    ReactDOM.render(        <App />,        document.getElementById('app')    );</script></body>
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/375786.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号