基于react框架使用的一些细节要点的思考
这篇文章主要是写关于学习react中的一些自己的思考:
1.setstate到底是同步的还是异步的?
2.如何在子组件中改变父组件的state
3.context的运用,避免“props传递地狱”
4.组件类里有私有变量a,它到底改放在this.a中还是this.state对象中(作为属性a)呢?
1.setstate到底是同步的还是异步的?
class mycomponent extends react.component{ constructor(props) { super(props) this.state ={ value:0 } } handleclick = () => { this.setstate({value:1}) console.log('在handleclick里输出' + this.state.value); } render(){ console.log('在render()里输出' + this.state.value); return (<div> <button onclick ={this.handleclick}>按钮</button> </div>) } } export default mycomponent //省略渲染过程,下面也一样
在这里我们点击按钮时,调用handleclick函数,首先调用this.setstate()设置value,随即把this.state.value输出,结果是什么?
你可能会想,这还不简单——“在handleclick里输出1”呗,然而你错了,它的结果为:
事实上,setstate()的调用是异步的,这意味着,虽然你调用了setstate({value:0}),但this.state.value并不会马上变成0,而是直到render()函数调用时,setstate()才真正被执行。结合图说明一下:
我们对handleclick做一些修改,让它变得复杂一点,在调用handleclick的时候,依次调用handlestatechange1 ,handlestatechange2,handlestatechange3,它们会调用setstate分别设置value为1,2,3并且随即打印
handlestatechange1 = () => { this.setstate({value:1}) console.log('在handleclick里输出' + this.state.value); } handlestatechange2 = () => { this.setstate({value:2}) console.log('在handleclick里输出' + this.state.value); } handlestatechange3 = () => { this.setstate({value:3}) console.log('在handleclick里输出' + this.state.value); } handleclick = () => { this.handlestatechange1(); this.handlestatechange2(); this.handlestatechange3(); }
2.如何在子组件中改变父组件的state呢?
class son extends react.component{ render(){ return(<div onclick = {this.props.handleclick}> {this.props.value} </div>) } } class father extends react.component{ constructor(props){ super(props) this.state ={ value:'a' } } handleclick = () => { this.setstate({value:'b'}) } render(){ return (<div style ={{margin:50}}> <son value = {this.state.value} handleclick = {this.handleclick}/> </div>) } }
class son extends react.component{ render(){ return (<h3 style ={{margintop:30}}>我从我的爷爷那里得到了基因--{this.props.gene}</h3>) } } class father extends react.component{ render(){ return (<son gene = {this.props.gene}/>) } } class grandfather extends react.component{ constructor(props) { super(props) this.state ={ gene:'[爷爷的基因]' } } render(){ return (<father gene = {this.state.gene}/>) } }
class son extends react.component{ render(){ console.log(this.context.color); return (<h3 style ={{margintop:30}}>我从我的爷爷那里得到了基因--{this.context.gene}</h3>) } } son.contexttypes ={ gene:react.proptypes.string } class father extends react.component{ render(){ return (<son/>) } } class grandfather extends react.component{ getchildcontext(){ return {gene:'[爷爷的基因]'} } render(){ return (<father />) } } grandfather.childcontexttypes = { gene: react.proptypes.string }; export default grandfather
getchildcontext(){ return {type:this.state.type} }
const proptypes = require("prop-types"); grandfather.childcontexttypes = { gene: proptypes.string };
以上这篇基于react框架使用的一些细节要点的思考就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
上一篇: 五个美足方法 让双脚精致美白
下一篇: 怎样促进胸部发育 明确四点丰乳有道