class AjaxInConstructor extends React.Component{ constructor() { super(); this.state = {name: '',age: ''} this.loadData().then(data => { this.setState(data); }); } loadData() { return new Promise((resolve,reject) => { setTimeout(() => { resolve({ name: '我去去去去nimabi',age: 123 }); },2000); }); } render() { const {name,age} = this.state; return <div> <p>Can I init component state async?</p> <p>name: {name}</p> <p>age: {age}</p> </div> } } ReactDOM.render( <AjaxInConstructor/>,document.body )
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
以上是我的演示代码.我知道人们总是把ajax放在componentDidMount或componentWillMount生命周期中.
但这种情况也有效.