如何在React JS的JSX内部处理Promise?

时间:2018-06-28 03:41:09

标签: javascript reactjs es6-promise

这是我第一次在React JS项目中处理JSX内部的诺言。

这是我的组件代码。

import React from 'react';
import Sodexo from './Sodexo';
import { connect } from 'react-redux';
import {withCookies} from 'react-cookie';

import ticketImg from './../../images/web-images/ticketrest.png';
import sodexImg from './../../images/web-images/sodexo.png';

import {selectMealVoucher} from './../../actions/paymentActions';
import {getSavedCard} from './../../utils/PaymentGateway';


class MealVoucher extends React.Component {

    checkCardSaved = async () => {
        const {cookies} = this.props.cookies;
        const card = await getSavedCard(cookies.id,cookies.token);
        const {sodexo} = card.data;

        return sodexo.length === 0 ? 0 : 1;
    }

    render() {
        const {sodexo, ticketrestaurant} = this.props;
        return (
            <div>
                <div class="row">
                    <div className="col-md-1 col-sm-1"></div>
                    <div class="col-md-5 col-sm-5">
                        <div class="form-group">
                            <input 
                                type="radio" 
                                name="mealvoucher"
                                {...sodexo.isActive ? {checked: true} : {}} 
                                onChange={() => this.props.selectMealVoucher('sodexo')}
                            />
                            <img src={sodexImg} height="30px" style={{marginLeft:'15px'}}/>
                        </div>
                    </div>

                    <div class="col-md-5 col-sm-5">
                        <div class="form-group">
                            <input 
                                type="radio" 
                                name="mealvoucher"
                                {...ticketrestaurant ? {checked: true} : {}} 
                                onChange={() => this.props.selectMealVoucher('ticketrestaurant')}
                            />
                            <img src={ticketImg} height="30px" style={{marginLeft:'15px'}} />
                        </div>
                    </div>
                </div>

                {
                    sodexo.isActive ? (
                       this.checkCardSaved().then(res => {
                           res ? <Sodexo /> : ''
                       })
                    ): ''
                }

            </div>
        );
    }
}

const mapStateToProps = state => state.paymentpage.paymentoption.mealvouchers;
const mapDispatchToProps = {selectMealVoucher};

export default withCookies(connect(mapStateToProps,mapDispatchToProps)(MealVoucher));

在上面,我试图在JSX中调用checkSavedCard(),但是即使我从0返回了1checkSavedCard(),我仍然看到了这个承诺返回而不是01

因此,我使用了.then()并尝试根据checkSavedCard()返回的值来渲染另一个组件。

但是,这不起作用,相反,我收到一条错误消息。

Objects are not valid as a React child (found: [object Promise]).

因此,我想出了另一种方法。 我在checkSavedCard()内创建了一个全局变量,而不是将值保存到全局变量中,而没有返回该值,然后在JSX中,我正在检查该全局变量的值。

这种方法对我来说很好。

这是工作组件代码。

import React from 'react';
import Sodexo from './Sodexo';
import { connect } from 'react-redux';
import {withCookies} from 'react-cookie';

import ticketImg from './../../images/web-images/ticketrest.png';
import sodexImg from './../../images/web-images/sodexo.png';

import {selectMealVoucher} from './../../actions/paymentActions';
import {getSavedCard} from './../../utils/PaymentGateway';


class MealVoucher extends React.Component {
    cardStatus;

    componentDidMount() {
        this.checkCardSaved();
    }

    checkCardSaved = async () => {
        const {cookies} = this.props.cookies;
        const card = await getSavedCard(cookies.id,cookies.token);
        const {sodexo} = card.data;

        this.cardStatus = sodexo.length === 0 ? 0 : 1;
    }

    render() {
        const {sodexo, ticketrestaurant} = this.props;
        return (
            <div>
                <div class="row">
                    <div className="col-md-1 col-sm-1"></div>
                    <div class="col-md-5 col-sm-5">
                        <div class="form-group">
                            <input 
                                type="radio" 
                                name="mealvoucher"
                                {...sodexo.isActive ? {checked: true} : {}} 
                                onChange={() => this.props.selectMealVoucher('sodexo')}
                            />
                            <img src={sodexImg} height="30px" style={{marginLeft:'15px'}}/>
                        </div>
                    </div>

                    <div class="col-md-5 col-sm-5">
                        <div class="form-group">
                            <input 
                                type="radio" 
                                name="mealvoucher"
                                {...ticketrestaurant ? {checked: true} : {}} 
                                onChange={() => this.props.selectMealVoucher('ticketrestaurant')}
                            />
                            <img src={ticketImg} height="30px" style={{marginLeft:'15px'}} />
                        </div>
                    </div>
                </div>

                {
                    sodexo.isActive && this.cardStatus ? (
                       <Sodexo />
                    ): ''
                }

            </div>
        );
    }
}

const mapStateToProps = state => state.paymentpage.paymentoption.mealvouchers;
const mapDispatchToProps = {selectMealVoucher};

export default withCookies(connect(mapStateToProps,mapDispatchToProps)(MealVoucher));

但是我认为这不是一个完美的解决方案,React JS可能提供了一些东西来处理JSX内部的承诺。

我用谷歌搜索,但没有找到任何解决方法。

1 个答案:

答案 0 :(得分:4)

React无法根据Promise的结果进行渲染。您应该更新组件状态中的值,并根据状态值进行渲染。在这里查看我的示例:https://codesandbox.io/s/1vzon8r4k4。单击按钮会将状态设置为loading: true(只是为了在用户等待时向用户显示一些信息),然后触发异步调用。异步调用完成后,状态会更新为设置loading: false并将异步调用的结果设置为状态中的值。更新状态后,将自动调用render函数,并更新UI以反映状态变化。

const fakePromise = () =>
  new Promise((resolve, reject) => {
    const fakeResult = "Complete";
    setTimeout(() => resolve(fakeResult), 1000);
  });

class App extends React.Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      loading: false,
      result: null
    };

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

  startAsync() {
    this.setState({
      loading: true
    });

    fakePromise().then(result =>
      this.setState({
        loading: false,
        result
      })
    );
  }

  render() {
    const { loading, result } = this.state;
    return (
      <div className="App">
        {!result &&
          !loading && (
            <div>
              <h1>Result Not Fetched</h1>
              <button onClick={this.startAsync} type="button">
                Fetch Result Async
              </button>
            </div>
          )}
        {loading && <h1>Fetching Result</h1>}
        {result && <h1>Result is: {result}</h1>}
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>