为什么我们不写
axios
.get('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => this.setState({ albums: response.data }));
在render
方法中,我们是否必须将其放入componentWillMount
?
如果我们把它放在render
方法的开头会有什么问题?
我把它放在render
中并得到了相同的结果,但教程说它应该在componentWillMount
。
答案 0 :(得分:3)
一般情况下,两者之间的区别在于多少次您要提出此请求。
如果您希望仅在第一次安装组件时发生请求,您将使用ComponentWillMount
(首选)
如果您希望在每个渲染上发生请求(不鼓励),请使用render
方法。
在你的情况下,将它放在render
方法中实际上会导致无限递归,因为每个请求都会调用setState
,这将导致重新呈现,这将产生将调用{{1这将导致重新渲染...
更不用说性能成本以及来自如此多频繁请求的网络拥塞。
setState

class Example extends React.Component {
constructor() {
super()
this.state = {
counter: 0
}
}
render() {
// fake async action to act as a request
setTimeout(() => {
const { counter } = this.state;
this.setState({
counter: counter + 1
})
}, 500)
return React.createElement('h3', null, this.state.counter)
}
}
ReactDOM.render(
React.createElement(Example),
document.querySelector('#example')
)