![](/img/trans.png)
[英]React Native cloned child component is not being rerendered as props change
[英]React Native Redux. State is being updated, yet the component is not being rerendered
我正在使用Redux開發應用程序。
在以下代碼片段中,我切換了appEnabled狀態:
...
render() {
const { appEnabled } = this.props;
const { updatePreferences } = this.props;
return (
<View style={styles.preferences}>
<Text>App enabled: {appEnabled + ''}</Text>
<Button onPress={() => updatePreferences({ appEnabled: !appEnabled })}>Toggle AppEnabled</Button>
</View>)
}
以下是映射函數:
function mapStateToProps({ preferences }) {
return {
appEnabled: preferences.appEnabled,
};
}
function mapDispatchProps(dispatch) {
return {
getPreferences,
updatePreferences: (preferences) => dispatch(updatePreferencesAction(preferences))
};
}
export default connect(mapStateToProps, mapDispatchProps)(PreferenceScreen);
狀態的更新工作正常。 但是,組件的重新渲染不會發生。
我知道常見原因可能是偶然的狀態突變。 我確保reducer函數每次都返回新對象:
export default function preferenceReducer(state = { ...defaultState }, action = {}) {
// console.log("reduces is called")
switch (action.type) {
case UPDATE_PREFERENCES :
return { ...state, ...action.preferences };
default:
return state;
}
}
// Action creators
export function updatePreferencesAction(preferences) {
return { type: UPDATE_PREFERENCES, preferences };
}
在我的情況下,不重新渲染組件的原因可能是什么?
如果不查看完整代碼,很難分辨出來,如果添加jsfiddle,則更容易獲得幫助。
無論如何,您的組件看起來不錯,並且應該在道具更改時更新。 在Reducer中更新狀態的方式似乎唯一有些奇怪。 我不能僅通過查看減速器來判斷狀態的形狀,但是,例如,為什么要執行state = {...defaultState}
而不是state = defaultState
?
return {...state, ...action.preferences }
也令人懷疑。 在大多數情況下,狀態的更新是這樣的: return { ...state, preferences: action.preferences }
因為它使您的reducer變得更加清晰。
我建議您進行這些更改,然后使用redux devtools進行徹底調試。
更改
function mapStateToProps({ preferences }) {
return {
appEnabled: preferences.appEnabled,
};
}
至
function mapStateToProps({ appEnabled }) {
return {
appEnabled: appEnabled,
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.