2017-03-23 20 views

回答

0

關於這個問題,請閱讀Redux docs,但基本上它使每個更新都更加易用,這使得從測試到渲染都變得更簡單。

1

不,它不是更快。直接改變狀態通常更快。

返回一個新的狀態使得reducer更容易測試和預測(因爲沒有副作用),我們也可以防止一些意外的行爲發生。例如,如果您使用的是PureComponent,並且您直接改變狀態,則您的組件可能無法按預期更新,因爲PureComponent使用===來比較道具。

考慮下面的代碼,我們試圖呈現一個列表:

// current state 
const list = ['foo', 'bar'] 

// we mutate the state directly 
list[1] = 'hihi' 

// in shouldComponentUpdate of a PureComponent 
props.list === nextProps.list // true 

在這種情況下,組件將不會意識到更新。

除了PureComponent之外,在react-redux中還有一些優化依賴於這個約定。

+0

用你的例子,如果你不直接改變列表而是使用一個新列表,那麼新列表如何轉到nextProps並且舊列表是否保留了props? – stackjlei

+0

爲什麼不呢? Redux只是將新列表傳遞給組件 – CodinCat

+0

實際上,做出的反應非常簡單。 newProps將被分配給實例'inst.props = nextProps' – CodinCat

相關問題