react.js - 一个有关react的问题,困扰很久了

查看:140
本文介绍了react.js - 一个有关react的问题,困扰很久了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

直接上代码
Box:

class Box extends React.Component{
    constructor(props){
        super(props);
        this.state={
            name : 'Max'
        }
    }
    componentDidMount(){
        // let arrs = [];
        for(let i = 0;i < 20;i++){
            infos.push(<Box1 name={this.state.name}/>);
        }
        // this.setState({arrs:arrs});
        this.setState({});


    }
    render(){
        // let arrs = [];
        // for(let i = 0;i < 20;i++){
        //     arrs.push(<Box1 name={this.state.name}/>);
        // }
        return (
            <div>
                {infos}
                <input type="button" onClick={()=>{console.log(this);
                this.setState({name : 'aaa'})}} value="button"/>
            </div>

        )
    }
}
Box1:
class Box1 extends React.Component{
constructor(props){
    super(props);
    this.state={
        name : 'Max'
    }
}
componentWillReceiveProps(nextProps){
    console.log('next',nextProps);
}
render(){
    return (
        <h1>
            hello world{this.props.name}
        </h1>
    )
}

}
如上所示,我在最上面写了个数组,然后为数组添加了20个子组件作为元素,
1.我想更新父组件中的state,可是结果没有触发子组件的componentwillreceiveprops,为什么?
2.在render方法里面写的新的添加数组的元素,这样就能触发了,想知道这两种是什么区别
3.一直说组件挂载,那我每次往数组里push的应该都是新的组件啊,可是结果并不是,这又是什么原因
小白求教,望有大神拖走。

解决方案

我想,问题1与2是一样的,关键在于你在componentDidMount里面作接下来的更新是没用的。

componentDidMount只会在第一次渲染时调用,之后并不会调用,里面是用来作初始化组件资料用的。所以自然不会触发子组件的componentWillReceiveProps

写在render里面才是有用处的,每次调用setState是如果有更新的情况,会接著调用render

问题3.不是太理解,猜测是你在componentDidMount调用了setState造成的。

附张生命周期图,参考一下吧: https://medium.com/@eddychang...

下面是测试过可执行的代码:

class Box extends React.Component{

    constructor(props){
        super(props);
        this.state={
            name : 'Max'
        }
     }

    componentDidMount(){
        // let arrs = [];
        // for(let i = 0; i < 20;i++){
        //     infos.push(<Box1 key={i} name={this.state.name}/>);
        // }
        // this.setState({arrs:arrs});
        //this.setState({});
    }

    render(){
        let arrs = [];
        for(let i = 0;i < 20;i++){
            arrs.push(<Box1 key={i} name={this.state.name}/>);
        }
        return (
            <div>
                {arrs}
                <input type="button" onClick={()=>{ console.log(this);
                  this.setState({name : 'aaa'});} } value="button"/>
            </div>
        )
    }
}

class Box1 extends React.Component{
  constructor(props){
      super(props);
      this.state={
          name : 'Max'
      }
  }
  componentWillReceiveProps(nextProps){
      console.log('next',nextProps);
  }
  render(){
      return (
          <h1>
              hello world{this.props.name}
          </h1>
      )
  }
}

ReactDOM.render(<Box />, document.getElementById("root"))

这篇关于react.js - 一个有关react的问题,困扰很久了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆