class Foo extends Component {
constructor(props) {
super(props);
this.state = { loading: true };
}
async componentDidMount() {
const data = await loadStuff();
this.setState({ loading: false, data });
}
render() {
const { loading, data } = this.state;
return (
{loading ? <Loading /> : <View {...data} />}
);
}
}
class Foo extends Component {
state = { loading: true };
...
}
此处仍存在构造函数,你只是看不见而已。绑定方法使用 constructor 的另一重原因是将函数绑定到 this,如下所示。
class Foo extends Component {
constructor(props) {
super(props);
this.myHandler = this.myHandler.bind(this);
}
myHandler() {
// some code here that references this
}
...
}
class Foo extends Component {
myHandler = this.myHandler.bind(this);
myHandler() {
// some code here that references this
}
...
}
class Foo extends Component {
constructor(props) {
super(props);
this.state = {
color: this.props.initialColor
};
}
render() {
const { color } = this.state;
return (
<div>
{color}
</div>
);
}
}
class Foo extends Component {
state = {
color: this.props.initialColor
};
...
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |