我試圖瞭解一些關於反應的內容,並希望能夠通過更好的方式獲得想法。渲染與生命週期方法中的反應計算
基本上,我想對傳入的道具做一些轉換/計算。目前我基於事件的狀態變化有限,但未來可能會發生變化。基本上,在渲染,componentWillMount和componentWillReceiveProps和set state中做這些計算會更好嗎?
在渲染例如:
render() {
var url = this.getUrl() // get url transforms some props into a valid url
var something = this.getSomething() // etc etc
return <a href={url}>{something}</a>
}
之外渲染:
componentWillMount() {
this._checkAndSetUrl(this.getUrl(this.props.data));
},
componentWillReceiveProps(nextProps) {
const currentGivenUrl = this._getUrl(this.props.data)
const nextGivenUrl = this._getUrl(nextProps.data)
if (currentGivenUrl !== nextGivenUrl) {
this._checkAndSetUrl(nextGivenUrl);
}
},
_checkAndSetUrl(url) {
// check validity and do some stuff to url
url = "new url"
something = this.getSomething()
this.setState({url: url, something: something})
}
我的想法是第二種方式是更好,因爲你不這樣做的計算上的每個渲染,只有當事情改變。接受的方式是什麼?
是的,它通常建議你不要把計算數據進入狀態,而是重新計算它的渲染。請參閱https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#what-shouldnt-go-in-state – Brandon
另外,最好在'componentWillReceiveProps()'生命週期特定只有東西:你需要當前'this.props'以及下一個道具的東西,或者你需要根據新的道具更新狀態的東西。 – wintvelt