react中 componentWillMount,componentDidMount有什么用处?

rt

        var Diver = React.createClass({
            getInitialState:function(){
                    return (styles = {
                        width:'100%',
                        height:'100%',
                        background:'red',
                        position:'fixed'
                    })
                },
            componentWillMount:function(){
                alert('ok')
            },
            render:function(){
                return (
                    <div className = 'container' style={this.state}>{this.props}</div>
                    )
            },
            componentDidMount:function(){
                alert('OK')
            }
        });
        React.render(
            <Diver name = 'myname'/>,
            document.querySelector('.wrap')

componentWillMount与componentDidMount这两个函数的作用是什么?还望大家赐教

阅读 8.1k
3 个回答

will是在render之前调用,did是在render之后调用,具体有什么用要看你在function里面怎么写。比如,will里面请求数据,did在告诉服务器render已经完成

官方文档有详细说明,两者主要区别是调用顺序,一个在render之前,一个在render之后。另外,官方建议是,用constructor()替换componentWillMount
clipboard.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题