componentDidMount()
-
之所以react推荐在componentDidMount钩子中使用而不是componentWillMount的原因:因为请求是异步的,所以无论你放在两个中的任何一个里面,几乎绝对都会在组件渲染之后,再进行数据渲染,也就是说避免不了二次渲染(第一次渲染为默认值,第二次为请求后的数据渲染),所以效果上放到哪里都一样,但是在DidMount中可以使用refs了。然后重要的是(是在Stack Overflow中的回答看到):未来的react版本可能会对componentWillMount进行调整,可能在某些情况下触发多次,所以官方是推荐在componentDidMount中进行请求。 当然放到willMount中可能会快那么几毫秒,毕竟先运行嘛。。。
-
vue的渲染前的钩子函数比react多两个:beforeCreat与created。而vue的例子为什么在created中写的,可能是因为是个demo也没有考虑那么多。一样的道理,无论放到beforeCreat、created或者beforeMount中也同样避免不了二次渲染,差别也可能是那么几毫秒
You should do requests in componentDidMount.
- If componentWillMount is called before rendering the component, isn't it better to make the request and set the state here?
No because the request won’t finish by the time the component is rendered anyway.
- If I do so in componentDidMount, the component is rendered, the request is made, the state is changed, then the component is re-rendered. Why isn't it better to make the request before anything is rendered?
Because any network request is asynchronous. You can't avoid a second render anyway unless you cached the data (and in this case you wouldn't need to fire the request at all). You can’t avoid a second render by firing it earlier. It won’t help.
In future versions of React we expect that componentWillMount will fire more than once in some cases, so you should use componentDidMount for network requests.
箭头函数 vs 普通函数
Arrow function
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}));
this.setState(function(prevState, props) {
return {
counter: prevState.counter + props.increment
}
})
状态更新合并
构造
constructor(props) {
super(props)
this.state = {
posts: [],
comments: []
}
}
更新
commponentDidMount() {
fetchPosts().then( response => {
this.setState({
posts: response.posts
})
} )
fetchComments().then( response => {
this.setState({
comments: response.comments
})
} )
}
网友评论