更新Redux State&然后获取相同实例中的更新状态

时间:2016-05-02 08:34:51

标签: javascript reactjs state redux react-redux

情景:

我有一个带有子图像的响应式div容器(CSS - 宽度:33%)。不希望用户向下滚动,我想找出div的绝对尺寸,以便我可以计算出适合的图像数量(具有固定的宽度和高度)。然后渲染只有可以放在屏幕上的图像。

我正在使用React& Redux这个应用程序。这是我想到的逻辑,它不起作用。

_ Smart Component (subscribed to the Store)
|___ `div` container (presentational component)
|______ images (presentational components)

我渲染'presentational'组件,然后在componentDidMount中,我发出一个找出宽度和宽度的函数。 div容器的高度&使用“图像容量”值更新Redux状态(可以在div容器中存储多少图像)。

在上述功能之后,在componentDidMount之后,我立即发送另一个应该从商店获取 UPDATED 值的功能(图像容量)&用图像数据更新商店。

这个想法是,当商店更新时,智能组件将重新呈现演示组件(div& images)&因此,将出现第二轮重新渲染以显示图像。

不幸的是,这是有缺陷的。传递给演示组件的道具是'更新前'存储值(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>&amp;的父级添加“智能组件”。然后让父母计算尺寸。但是,在这种情况下,道具仍然没有更新,这是可以理解的,因为componentDidMount是在<PreviewTemParent>安装后运行的。

以下是我根据@ pierrepinard_2关于使用componentWillReceiveProps的建议尝试的解决方案,似乎没有被调用。

C_PreviewTemParent CONTAINER(SMART COMPONENT)

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 );

PreviewParent COMPONENT

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>
        );
    }
});

行动创作者 请原谅冗长的代码:!

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
    });
};

最后,THE REDUCER

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;
    }
};

1 个答案:

答案 0 :(得分:1)

问题在于,当您在this.props.previewTemState中调用temImgToShow()时,状态对象引用仍然与componentDidMount()执行开始时相同,在调用this.props.findImgCapacity()之前

一个选项是仅从componentDidMount()触发一个合成动作,其中包含以下参数:width和height(用于计算图像容量),templateType,分页。然后,您只能获得一个具有所需状态的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中间件,则可以使用具有承诺的异步操作创建器来正确链接操作。如果你给我们你的行动代码,我可以告诉你如何去做。