更新Redux状态&然后在同一实例中获取更新状态

Update Redux State & Then Get The Updated State In Same Instance

本文关键字:状态 更新 实例 获取 然后 Redux amp      更新时间:2023-09-26

场景:

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

我正在使用React&此应用程序的Redux。这是我一直在思考的逻辑,它不起作用。

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

我呈现了"presentational"组件,然后在componentDidMount中,我调度了一个函数,该函数可以找到Width&CCD_ 4容器的高度&使用"图像容量"值(div容器中可以存储多少图像)更新Redux状态。

在上面的函数之后,当仍然处于componentDidMount中时,我立即调度另一个函数,该函数应该从存储(图像容量)&用图像数据更新商店。

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

不幸的是,这是有缺陷的。传递给表示组件的道具是"预更新"存储值(0),因此当我运行dispatch第二个函数用图像更新存储时,其道具中的"图像容量"值仍然为零(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>&然后让家长计算尺寸。然而,在这种情况下,道具仍然没有更新,这是可以理解的,因为组件DidMount是在安装<PreviewTemParent>之后运行的。

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

C_PreviewTemParent CONTAINER(智能组件)

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

动作创建者请原谅代码太长:!

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()中只触发一个合成操作,参数如下:宽度和高度(用于计算图像容量)、templateType、分页。然后,您将只获得一个具有所需状态的UI更新。

如果你真的不能只触发一个动作来执行所有的工作,那么你可以像Honza Haering在评论中建议的那样,在componentWillReceiveProps()中触发第二个动作:

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中间件,您可以使用异步操作创建者,并承诺正确地链接操作。如果你给我们你的行动代码,我可以向你展示如何做到这一点。