【问题标题】:dispatching the `retrieveSportsDetails` function, but I’m not sure how to write the `if` condition调度 `retrieveSportsDetails` 函数,但我不知道如何编写 `if` 条件
【发布时间】:2016-12-26 13:53:06
【问题描述】:

我是新来的反应。我正在使用 redux,我正在使用它在减速器中编写动作和减速器我正在设置状态,在我的代码中使用该状态我需要编写一个条件。如果是真的,我需要显示函数renderAutomaticSports 或者不在componentWillMount 中显示函数renderAutomaticSports

我正在调度retrieveSportsDetails 函数,但我不确定如何编写if 条件。

  • 你们能告诉我如何把渲染功能放在里面吗? 条件

    componentWillReceiveProps(nextProps) { if(nextProps.state.isAutomaticSportsSet && !this.props.profile.isAutomaticSportsSet ) { //renderAutomaticDeposit(); } }

代码 sn-p 如下。你能帮帮我吗?

import React, {Component} from 'react';
import {moneyFormat} from '../../common/mixin-money-format';
import {connect} from 'react-redux';
import moment from 'moment';
import '../../../css/basketball-tracker-tile.css';
import {retrieveSportsDetailsRequest} from '../../../redux/activity/details/activity-details-actions';
import {retrieveSportsDetails} from '../../../redux/automatic-deposits/automatic-deposits-actions';


class sportsProfile extends Component {

    constructor(props) {
        super(props);

        this.editHandler = this.editHandler.bind(this);
    }

    editHandler() {
        this.props.onEdit();
    }

    renderProgressError() {
        return (
            <div className="text-center negative">
                Account Information Unavailable
            </div>
        );
    }

    componentWillMount() {
        //debugger;
        this.props.dispatch(retrieveSportsDetails());

    }

    renderProgress(data) {
        const circumferenceOfCircle = 1131;
        // negative or no growth
        const progressMade = Math.floor((data.accumulatedAmount * 100) / data.basketballAmount) || 0;

        let progressMadePercent = ((progressMade / 100) * circumferenceOfCircle);
        let achievementStyle;
        let growthAngle = 'rotate(-90 208.6 206.4)';

        if (data.accumulatedAmount > data.basketballAmount) {
            // exceed the expected growth
            achievementStyle = 'platinumAchievementCircle';
        } else if (data.accumulatedAmount > 0) {
            // positive growth
            achievementStyle = 'goldAchievementCircle';
        } else {
            // negative growth
            achievementStyle = 'negAchievementCircle';
            growthAngle = 'rotate(150 208.6 206.4)';

            // doing this for the purpose of showing the negative growth
            progressMadePercent = -progressMadePercent;
        }

        const progressMadeStyle = {
            strokeDasharray: progressMadePercent + ' ' + circumferenceOfCircle
        };

        return (
            <div className="progress_container">
                <svg x="0px" y="0px" viewBox="0 0 420 420">
                    <circle id="blue_circle" className="blueBackCircle" cx="208.6"
                        cy="206.4" r="180.2"
                    />
                    <path id="track" className="blueTrackCircle"
                        d="M208.6,35.7c-94.3,0-170.7,76.4-170.7,170.7s76.4,170.7,170.7,170.7s170.7-76.4,170.7-170.7
                            S302.9,35.7,208.6,35.7z M208.6,368.6C119,368.6,46.4,296,46.4,206.4S119,44.3,208.6,44.3s162.2,72.6,162.2,162.2
                            S298.2,368.6,208.6,368.6z"
                    />
                    <circle
                        id="golden_progress_circle" className={achievementStyle}
                        style={progressMadeStyle} cx="208.6" cy="206.4"
                        r="180.2" transform={growthAngle}
                    />
                </svg>
                <div className="progress_number">
                    {progressMade}% <span className="accessibility-hidden">basketball progress</span>
                </div>
            </div>
        );
    }


    renderTarget() {
        const name = this.props.profile.firstName;
        return (
            <div className="alert-box action-shadow">
                <h4>{`Want some advice${name && name.length > 0 ? `, ${name}` : ''}?`}</h4>
                <p>Stay focused by setting a target date for completion of your basketball.</p>
                <div className="secondary-links section_content">
                    <a href="javascript:;" onClick={this.editHandler}>Set Target Date</a>
                </div>
            </div>
        );
    }

    renderAutomaticSports() {
        const name = this.props.profile.firstName;
            return (
                <div className="alert-box action-shadow">
                    <h4>{`Want a helpful tip${name && name.length > 0 ? `, ${name}` : ''}?`}</h4>
                    <p>Add some momentum to your account by setting up automatic recurring deposits.</p>
                    <div className="secondary-links section_content">
                        <a href="javascript:;" onClick={this.editHandler}>Set Up Automatic Sportss</a>
                    </div>
                </div>
            );
    }

    renderGoalDate(basketballEndDate) {
        return (
            <div>
                <h3 className="top15">Goal Target Date</h3>
                <p>
                    {moment(basketballEndDate).format(sportsProfile.static.displayDateFormat)}
                </p>
            </div>
        );
    }

    render() {
        const {basketballDetails, data} = this.props;
        const basketballAmount = parseFloat(basketballDetails.basketballAmount);
        const accumulatedAmount = data.summary.total || 0;

        return (
            <div>
                <div className="content-box action-shadow">
                    {
                        basketballDetails.error ?
                            this.renderProgressError() :
                            this.renderProgress({
                                accumulatedAmount,
                                basketballAmount
                            })
                    }
                    <div className="section_content">
                        <h2>Your Goal Progress</h2>
                        <p>You have accumulated <strong className={accumulatedAmount >= 0 ? null : 'negative'}>
                            {moneyFormat(accumulatedAmount)}</strong> towards your basketball of <strong>
                            {moneyFormat(basketballAmount)}</strong>.
                        </p>
                        {
                            basketballDetails.basketballDate && basketballDetails.basketballDate.length > 0 &&
                            basketballDetails.basketballDate !== '2199-01-01' && this.renderGoalDate(basketballDetails.basketballDate)
                        }
                        <div className="secondary-links section_content">
                            <a href="javascript:;" onClick={this.editHandler}>Edit Goal Details</a>
                        </div>
                    </div>
                </div>
                {basketballDetails.basketballDate && basketballDetails.basketballDate.length > 0 && basketballDetails.basketballDate !== '2199-01-01' ?
                    this.renderAutomaticSports() : this.renderTarget()}
            </div>
        );
    }
}

sportsProfile.propTypes = {
    data: React.PropTypes.object.isRequired,
    basketballDetails: React.PropTypes.shape({
        error: React.PropTypes.object,
        basketballId: React.PropTypes.number,
        basketballName: React.PropTypes.string,
        basketballAmount: React.PropTypes.number,
        basketballDate: React.PropTypes.string,
        isRetrieving: React.PropTypes.bool
    }),
    onEdit: React.PropTypes.func.isRequired,
    profile: React.PropTypes.object
};

sportsProfile.static = {
    displayDateFormat: 'MMM-YYYY'
};


export default connect(state => ({
    profile: state.template.profile,
    deposit: state.isAutomaticSportsSet
}))(sportsProfile);

减速器:

import {CONSTANTS} from './automatic-deposits-actions';

const initialState = Object.freeze({
    'deposit': false,
    'isRetrieving': true,
    'error': null
});

console.log("inside-automatic-deposits-------->");

export default function isAutomaticSportsSet(state = initialState, action) {
    switch (action.type) {
        case CONSTANTS.RETRIEVE_ACTIVITY_ATTEMPT:
            return Object.assign({}, state, {
                error: null,
                isRetrieving: true,
                accountId: action.accountId
            });
            console.log("CONSTANTS.RETRIEVE_ACTIVITY_ATTEMPT");

        case CONSTANTS.RETRIEVE_ACTIVITY_SUCCESS:
            return Object.assign({}, state, {
                deposit: action.response,
                error: null,
                isRetrieving: false
            });
            console.log("CONSTANTS.RETRIEVE_ACTIVITY_ATTEMPT");

        case CONSTANTS.RETRIEVE_ACTIVITY_FAILED:
            return Object.assign({}, state, {
                error: action.error,
                isRetrieving: false
            });
            console.log("CONSTANTS.RETRIEVE_ACTIVITY_ATTEMPT");

        default:
            return state;
            console.log("CONSTANTS.RETRIEVE_ACTIVITY_ATTEMPT");

    }
}

行动:

import * as Service from '../../components/common/services';

console.log("inside-automatic-actions");

const CONSTANTS = Object.freeze({
    RETRIEVE_ACTIVITY_ATTEMPT: 'retrieve_activity_attempt',
    RETRIEVE_ACTIVITY_SUCCESS: 'retrieve_activity_success',
    RETRIEVE_ACTIVITY_FAILED: 'retrieve_activity_failed'
});

const depositActivityRequest = (accountId) => {
    return {accountId, type: CONSTANTS.RETRIEVE_ACTIVITY_ATTEMPT};
};

const depositActivityRequestSuccess = (response) => {
    return {response, type: CONSTANTS.RETRIEVE_ACTIVITY_SUCCESS};
};

const depositActivityRequestFailure = (error) => {
    return {error, type: CONSTANTS.RETRIEVE_ACTIVITY_FAILED};
};

const retrieveSportsDetails = (accountId) => {
    return (dispatch, getState) => {
        dispatch(depositActivityRequest(accountId));
        //debugger;
        return Service.retrieveSportsDetails(getState());
    };
};

const retrieveSportsDetailsRequest = (accountId) => {
    return dispatch => {
        return dispatch(retrieveSportsDetails(accountId))
            .then(
                response => {
                    const activityList = response.data;
                    dispatch(depositActivityRequestSuccess(activityList));
                },
                error => {
                    //TODO add logging
                    //sportsLogger.error(error, 'Error retriving Activity details for the deposit');
                    dispatch(depositActivityRequestFailure(error));
                }
            );
    };
};

export {
    retrieveSportsDetailsRequest, retrieveSportsDetails, CONSTANTS
};

【问题讨论】:

    标签: javascript html css reactjs redux


    【解决方案1】:

    if 条件应该是 render() 的一部分。

    let sportsComponent;
    if (true) {
      sportsComponent = this.renderAutomaticSports();
    }
    

    要显示 sportsComponent,请将其包含在 JSX 中。

    { sportsComponent }
    

    【讨论】:

    • 但是我们没有收到reducer的财产押金...你能告诉我如何把它放在componentWillReceiveProps ` componentWillReceiveProps(nextProps) { if(nextProps.state.isAutomaticSportsSet && !this.props .profile.isAutomaticSportsSet ) { //renderAutomaticDeposit(); } } `
    猜你喜欢
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 2017-08-20
    • 2023-04-08
    • 1970-01-01
    相关资源
    最近更新 更多