正确使用react的refs/props/state及其它

来源:互联网 发布:剑灵茱莉亚身体数据 编辑:程序博客网 时间:2024/05/16 05:32

正确使用refs

很多人写refs是这么写的(代码仅作演示)http://www.jianshu.com/p/193c34e5eeeb

let Progress = React.createClass({    show: function(){        this.refs.modal.show();    },    render: function() {        return (           <ProgressFormModal ref="modal"/>        );    }});

但实际上这种写法已不建议使用,正确的写法应该如下:

let Progress = React.createClass({    show: function(){        this.modal.show();//注意这儿的this.refs.modal已被替换成this.modal    },    render: function() {        return (           <ProgressFormModal ref={ com => { this.modal=com } }/>        );    }});

官方不建议滥用refs,所以上面的代码其实还可以做优化,用props去更新ProgressFormModal的显示状态

正确使用props和state

很多人都知道不能直接修改state的状态

this.state.comment = 'Hello';//不正确的更新

但对于props和state还是有不少误用,很多人没有意识到props和state可能是异步的,比如:

//可能失败this.setState({  counter: this.state.counter + this.props.increment,});

正确的用法是

this.setState((prevState, props) => ({  counter: prevState.counter + props.increment}));

另外setState可能不会立即修改this.state,如果你在setState之后立马使用this.state去取值可能返回的是旧的值。setState这个方法其实可以接收两个参数,如下形式:

setState(nextState, callback)

它接收一个callback,它状态得到更新后,会执行这个callback,不过更推荐在componentDidUpdate中调用相关逻辑

避免产生新的闭包

在子组件中,我们要避免以下写法

<input            type="text"            value={model.name}            onChange={(e) => { model.name = e.target.value }}            placeholder="Your Name"/>

应该这么写

<input            type="text"            value={model.name}            onChange={this.handleChange}            placeholder="Your Name"/>

这样可以避免每次父组件重新渲染的时候,创建新的函数

0 0
原创粉丝点击