时间:2021-10-28 10:25:27 | 栏目:JavaScript代码 | 点击:次
这篇文章主要是写关于学习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 };