[英]React-Redux connect() not updating component even when the state is changed without mutation
我有這個codepen ,其中store.subscribe()
工作, connect()
不起作用。 具體來說,組件不會使用新的道具進行更新。 我懷疑狀態突變,因為我認為connect()的淺層等式檢查可能忽略了變化。 但是,我正在使用Immutable.js
進行reducer中的狀態更改,並且我也在我的subscribe方法中進行了自己的ref檢查,並且每次更新時它都會有很小的不同。 我覺得這里肯定有一些顯而易見的東西......
零件:
class App extends React.Component{
...
}
const mapStateToProps = state => ({
alerts: state.alerts
});
const mapDispatchToProps = dispatch => ({
onAlert: (type, autoHide, message) =>
dispatch({ type: 'SHOW_ALERT', payload: { message, type, autoHide } })
});
const ConnectedApp = connect(mapStateToProps, mapDispatchToProps)(App);
減速器:
const alertsReducer = (alerts=Immutable.List(), { type, payload }) => {
switch (type){
case 'SHOW_ALERT':
if (!payload.message || R.trim(payload.message).length === 0){
throw new Error('Message cannot be empty.');
}
return alerts.push(payload);
default:
return alerts;
}
};
商店:
const store = createStore(combineReducers({ alerts: alertsReducer }), applyMiddleware(ReduxThunk.default));
渲染:
//** THIS DOESN'T WORK
// ReactDOM.render(<Provider store={store}><ConnectedApp /></Provider>, document.getElementById('main'));
//** THIS WORKS
store.subscribe(()=>{
render();
});
const render = () => {
ReactDOM.render(<App {...store.getState()} onAlert={
(type, autoHide, message) => store.dispatch({ type: 'SHOW_ALERT', payload: { message, type, autoHide } })
}/>, document.getElementById('main'));
};
render();
這是因為頂級狀態對象仍然具有相同的引用嗎? 我嘗試刪除Immutable.js
並使整個狀態使用reducer每次都返回一個新數組。 那還是行不通的。
版本:
react-redux@4.4.5
redux@3.5.2
react@15.3.1
如果你打開控制台,就會出現錯誤
addComponentAsRefTo(...):只有ReactOwner可以有refs。 您可能正在向組件的
render
方法中未創建的組件添加ref,或者您有多個React副本已加載
要解決這個問題,你應該在https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-with-addons.min.js和https://cdnjs.cloudflare.com/ajax/libs之間做出選擇。 /react/15.3.1/react.js ,因為React應該被添加到頁面一次。
之后,您需要從react-redux添加Provider。 您還需要在列表中添加關鍵道具。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.