[英]React, Redux, mapStateToProps and no rerendering despite state changes
我對Redux和React有一個奇怪的問題。 狀態正確地更改並且在mapStateToProps
我也獲得了正確的新狀態,但在映射之后組件將不會重新渲染。
這樣,組件不會重新渲染:
import React, { Component } from 'react';
import { connect } from 'react-redux';
class ListItem extends Component {
render() {
return (<li>{this.props.item.text}</li>);
}
}
const mapStateToProps = (state, ownProps) => {
return {
item: state.test.byID[ownProps.itemID]
};
}
export default connect(mapStateToProps)(ListItem);
但是,如果我分割項目組件重新渲染:
import React, { Component } from 'react';
import { connect } from 'react-redux';
class ListItem extends Component {
render() {
return(<li>{this.props.text}</li>);
}
}
const mapStateToProps = (state, ownProps) => {
return {
id: state.test.byID[ownProps.itemID].id,
text: state.test.byID[ownProps.itemID].text
};
}
export default connect(mapStateToProps)(ListItem);
我不知道為什么。
減速器:
const startState = {
byID: {
'a1': {id: 'a1', text: 'test1'},
'a2': {id: 'a2', text: 'test2'},
'a3': {id: 'a3', text: 'test3'},
'a4': {id: 'a4', text: 'test4'},
'a5': {id: 'a5', text: 'test5'},
'a6': {id: 'a6', text: 'test6'},
'a7': {id: 'a7', text: 'test7'},
},
all: ['a1', 'a2','a3', 'a4', 'a5', 'a6', 'a7']
};
export default function reducer(state = startState, action) {
switch (action.type) {
case 'ADD_TEXT':
const newState = {...state};
newState.byID[action.id].text = action.text;
return newState
default:
return state;
}
}
有任何想法嗎?
假設您要更改其中一個byID
數組對象中的text
字段。 使用您的代碼:
newState.byID[action.id].text = action.text;
您正在改變您的狀態,因此React可能在識別更改時遇到問題,因為item
prop中對象的引用不會更改,只會更改它的屬性。 如果進行淺層檢查,它就不會重新渲染,因為它“假設”對象根本沒有變化。
在第二種情況下,您將返回字符串類型的prop text
,因此不會像對象那樣進行淺層檢查,並且相等的比較===
將區分更改並正確地重新呈現組件。
有關更多說明,您可能需要查看React中的Immutability 。
通過傳播運營商維護不變性的想法:
const newState = {...state};
可以用於頂級引用,但不適用於嵌套的子對象:
對象傳播執行對象的淺表副本。 僅克隆對象本身,而不克隆嵌套實例。 JavaScript中對象休息/傳播屬性的簡單指南
雖然變異對象似乎是您提供的代碼中最容易出錯的部分,但是Component
React類可以深入調查對象更改( PureComponent
沒有),並且問題可能與另一個問題有關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.