![](/img/trans.png)
[英]How to get a functional component to update when Redux state gets updated?
[英]Update Redux State & Then Get The Updated State In Same Instance
場景:
我有一個帶有子圖像的響應式div
容器(CSS - 寬度:33%)。 不希望用戶向下滾動,我想找出div
的絕對尺寸,以便我可以計算可以容納的圖像數量(具有固定的寬度和高度)。然后只渲染可以適合屏幕。
我正在為此應用程序使用 React 和 Redux。 這是我想到的邏輯,它不起作用。
_ Smart Component (subscribed to the Store)
|___ `div` container (presentational component)
|______ images (presentational components)
我渲染了“展示性”組件,然后在componentDidMount
,我調度了一個函數來找出div
容器的寬度和高度,並使用“圖像容量”值更新 Redux 狀態(在div
容器中可以存儲多少圖像)。
在上述函數之后,仍然在componentDidMount
,我調度另一個函數,該函數應該從存儲(圖像容量)獲取更新值並用圖像數據更新存儲。
這個想法是,當商店更新時,智能組件將重新渲染展示組件( div
和圖像),因此會發生第二輪重新渲染以顯示圖像。
不幸的是,這是有缺陷的。 傳遞給展示組件的道具是“預更新”存儲值 (0),因此當我運行調度第二個函數以使用圖像更新存儲時,其道具中的“圖像容量”值仍然為零( 0)。
我想知道在這里實施什么正確的邏輯?
如果代碼更有意義,這里是展示組件代碼:
const PreviewTemParent = React.createClass({
componentDidMount : function() {
let elePreviewParent = ReactDOM.findDOMNode( this.refs.previewParent );
previewTemParentAttr.width = elePreviewParent.clientWidth;
previewTemParentAttr.height = elePreviewParent.clientHeight;
this.props.findImgCapacity();
this.temImgToShow( "body" );
},
temImgToShow : function( templateType ) {
let pagination = this.props.previewTemState.get( "pagination" );
let imgCapacity = this.props.previewTemState.get( "imgCapacity" );
console.log( "%c In `PreviewTemParent`, pag, imgCap & props are...", "color : gold", pagination, "; ", imgCapacity, "; ", this.props );
this.props.temImgToShow( templateType, pagination, imgCapacity );
},
render : function() {
return(
<div
className = "previewParent"
ref = "previewParent">
<div className = "previewContainer">
{ this.props.previewTemState.get( "temImg" ).map( ( imgObj ) => {
<PreviewTemImgContainer data = { imgObj } />;
} ) }
</div>
</div>
);
}
});
應@pierrepinard_2 的要求,我發布了詳細的代碼,希望能解釋我的嘗試。
我嘗試了一些方法,包括向<PreviewTemParent>
的父級添加一個“智能組件”,然后讓父級計算尺寸。 但是,在這種情況下,道具仍然沒有更新,這是可以理解的,因為在安裝<PreviewTemParent>
之后運行<PreviewTemParent>
。
這是我根據@pierrepinard_2 關於使用componentWillReceiveProps
建議嘗試的解決方案,它似乎沒有被調用。
C_PreviewTemParent 容器(智能組件)
import { connect } from "react-redux";
import { temImgToDisplayInContainer } from "../modcon/Actions.js";
import PreviewTemParent from "../component/temContainer/PreviewTemParent.jsx";
const mapStateToProps = ({ previewTemImgState }) => {
return({
previewTemState : previewTemImgState
});
};
const mapDispatchToProps = ( dispatch ) => {
return({
temImgToDisplayInContainer : ( templateType, activePage ) => {
dispatch( temImgToDisplayInContainer( templateType, activePage ) );
}
});
};
export const C_PreviewTemParent = connect( mapStateToProps, mapDispatchToProps )( PreviewTemParent );
預覽父組件
const PreviewTemParent = React.createClass({
componentDidMount : function() {
this.props.temImgToDisplayInContainer( "body" );
},
componentWillReceiveProps : function( nextProps ) {
console.log( "%c componentWillReceiveProps is...", "color: green", nextProps );
},
render : function() {
return(
<div className = "previewParent">
<div className = "previewContainer">
{ this.props.previewTemState.get( "temImg" ).map( ( imgObj ) => {
<PreviewTemImgContainer data = { imgObj } />;
} ) }
</div>
</div>
);
}
});
ACTION CREATOR請原諒冗長的代碼 :!
export const temImgToDisplayInContainer = ( templateType, activePage ) => {
// temImgCapacity finds out the number of images that can
// fit in the container based on the container's dynamic Width & Height.
// in order to make the func reusable, activePage is an optional parameter
// hence the `if`
let temImgCapacity;
if( activePage ){
temImgCapacity = findImgCapacityInPreviewTem( false );
} else {
temImgCapacity = findImgCapacityInPreviewTem( true );
}
// `previewTemImgData` is a store of static data of all the images.
// during development, this is being used instead of ajax calls etc
// `temImgData` stores the data only for the 'templates' we are interested in
let temImgData = previewTemImgData.get( templateType );
let counter = 1;
// `noOfTemplate` is how many images we will render
let noOfTemplate = temImgCapacity.get( "imgCapacity" );
let currentPage = activePage || temImgCapacity.get( "activePage" );
// `maxCounter` is for pagination, which is the last template to store
let maxCounter = currentPage * noOfTemplate;
let temStartFrom = (( currentPage * noOfTemplate ) - noOfTemplate ); // what template start number.
// get the tempales we are only interested in
let filteredTemImgData = temImgData.filter( ( templateObj ) => {
if (( counter <= maxCounter ) && ( counter >= temStartFrom )) {
counter++;
return( templateObj );
}
} );
// merging the data from above first line 'temImgCapacity' & the filtered
// temImgData
let payloadData = filteredTemImgData.merge(( temImgCapacity ));
return({
type : CURRENT_TEM_IMG,
payload : payloadData
});
};
最后,減速機:
const previewTemImgState = ( state = initialPreviewTemState, action ) => {
switch( action.type ) {
case( FIND_IMG_CAPACITY_IN_PREVIEW_TEM ) :
return(
state.set( "imgCapacity", action.payload.imgCapacity )
);
case( RENDER_TEM_IMG ) :
console.log( action.payload );
var newState = state.set( "temImg", action.payload.temImg );
console.log( "%c previewTemImgState is...", "color : red", state.get( "temImg" ), " ; ", newState.get( "temImg" ) );
return(
state.set( "temImg", action.payload )
);
default :
return state;
}
};
問題在於,當您在temImgToShow()
調用this.props.previewTemState
時,狀態對象引用仍然與componentDidMount()
執行開始時相同,在this.props.findImgCapacity()
被調用之前。
一種選擇是從componentDidMount()
僅觸發一個合成操作,並帶有以下參數:寬度和高度(用於計算圖像容量)、模板類型、分頁。 那么你只會得到一個具有所需狀態的 UI 更新。
如果你真的不能只觸發一個動作來執行所有的工作,那么你可以在componentWillReceiveProps()
中觸發第二個動作,正如 Honza Haering 在評論中建議的那樣:
componentDidMount: function() {
let elePreviewParent = ReactDOM.findDOMNode( this.refs.previewParent );
previewTemParentAttr.width = elePreviewParent.clientWidth;
previewTemParentAttr.height = elePreviewParent.clientHeight;
this.props.findImgCapacity();
},
componentWillReceiveProps: function(nextProps) {
let newImgCapacity = nextProps.previewTemState.get( "imgCapacity" );
let oldImgCapacity = this.props.previewTemState.get( "imgCapacity" );
if (newImgCapacity !== oldImgCapacity && newImgCapacity > 0) {
let pagination = nextProps.previewTemState.get( "pagination" );
nextProps.temImgToShow("body", pagination, newImgCapacity);
}
},
或者,如果您使用redux-thunk中間件,您可以使用帶有承諾的異步操作創建器來正確鏈接操作。 如果你給我們你的行為代碼,我可以告訴你如何去做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.