javascript - 调度 `retrieveSportsDetails` 函数,但我不确定如何编写 `if` 条件

标签 javascript html css reactjs redux

我是新手。我正在使用 redux,我正在编写 Action 和使用它的 reducer 在我正在设置状态的 reducer 中,在我的代码中使用该状态我需要编写一个条件。如果为真,我需要在 componentWillMount 中显示函数 renderAutomaticSports 或不显示函数 renderAutomaticSports

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

  • 你们能告诉我如何将渲染功能放在这个 if 中吗 条件

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

代码片段如下。你能帮帮我吗?

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

reducer :

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

最佳答案

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

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

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

{ sportsComponent }

关于javascript - 调度 `retrieveSportsDetails` 函数,但我不确定如何编写 `if` 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39038427/

相关文章:

html - 仅使用 css 设置禁用输入的样式

javascript - Protractor IE 11 错误 - 找不到元素

javascript - Chart.js 2.0 向数据集添加新属性

javascript - angular $parse 作为一个指令参数爆炸了

html - 如何通过css只选择div内的元素

javascript - 如何防止在javascript中自动多次调用onchange函数?

javascript - 将 javascript 和 css 存储在数据库中是个坏主意吗?

当覆盖设置为隐藏时,JavaScript 更新消失

css - 将自定义 CSS 添加到我的 Polylang 小部件并删除元素符号 - 使用 WordPress

javascript - 悬停时交叉淡入淡出提交按钮