简体   繁体   中英

Sails.JS globals in React.JS

I am having the following idea:

I want to display a bunch of Card-Components from Reactstrap. Every of this Card-Components features another component which displays an progress bar to show the time to reload. This works very well using an callback function to pass it to the child component which is triggered when the reload time is over.

Now I thought about how I can manage the data inside the Card-Component. The data is fetched from an third party API (simple JSON). I tried to implement this data-fetching logic in an Sails.JS Helper .

But I am not able to call the global sails object from inside this component. I enabled the sails object globally in config/globals.js :

/**
 * THIS FILE WAS ADDED AUTOMATICALLY by the Sails 1.0 app migration tool.
 * The original file was backed up as `config/globals-old.js.txt`
 */

 module.exports.globals = {
   _: require('lodash'),
   async: require('async'),
   models: true,
   sails: true
 };

So here is the Card-Component I am using:

import React, {Component} from 'react';
import { Card, CardBody, CardImg, CardText, CardHeader, CardFooter } from 'reactstrap';
import { Row, Col } from 'reactstrap';
import { Progress } from 'reactstrap';
import ProgressBar from './ProgressBar';

class MyCard extends Component {
    constructor(props) {
        super(props);
        console.log('Constructed card');
        this.state = {};
        this.progressUpdateCallback = this.progressUpdateCallback.bind(this);
        /*var sails = require(sails);*/
        this.thirdPartyInfo = sails.helpers.thirdPartyInfo();
    }

    progressUpdateCallback() {
        console.log('In callback');
    }

    componentDidMount() {
        console.log('Card component mounted');
    }

    render() {
        return(
            <Col xs={1} sm={2} md={3} lg={4} className="mx-auto">
                <Card className="mt-4">
                    <CardHeader>
                        <Row>
                            <Col xs={2} sm={2} md={2} lg={2}>
                                <img src={this.props.cardLogo} 
                                    className="float-left img-fluid" />
                            </Col>
                            <Col className="text-left">
                                <strong>{this.props.headerText}</strong>
                            </Col>
                        </Row>
                    </CardHeader>
                    <CardBody>
                        <CardText>{this.props.text}</CardText>
                    </CardBody>
                    <CardFooter>
                        <ProgressBar parentUpdateMillis={this.props.updateAfterSeconds * 1000} updateMillis="1000" callback={this.progressUpdateCallback} />
                    </CardFooter>
                </Card>
            </Col>
        );
    };
}

export default MyCard;

My ProgressBar component looks like:

import React, {Component} from 'react';
import { Progress } from 'reactstrap';

class ProgressBar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            reloadedCounter: 0,
            currentProgBarPercent: 0
        };
        this.updateProgBar = this.updateProgBar.bind(this);
    }

    updateProgBar() {
        if(this.state.currentProgBarPercent == 100) {
            if(typeof(this.props.callback) === 'function') {
                this.props.callback();
            }
            this.setState({
                reloadedCounter: 0,
                currentProgBarPercent: 0
            });

        } else {
            this.setState({
                reloadedCounter: this.state.reloadedCounter + 1,
                currentProgBarPercent: (this.state.reloadedCounter + 1) * (100 / (this.props.parentUpdateMillis / this.props.updateMillis))
            });
        }
    }

    componentDidMount() {
        setInterval(this.updateProgBar, this.props.updateMillis);
    }

    render() {
        return(
            <div>
                <Progress value={this.state.currentProgBarPercent} />
            </div>
        );
    };
}

export default ProgressBar;

And my helper:

var sprintf = require("sprintf-js").sprintf;

module.exports = {
  friendlyName: 'Some info',
  description: 'Returns some info',

  inputs: {
    what: {
      type: 'string',
      example: 'currentTime',
      description: 'Fetch with information',
      required: true
    }
  },

  exits: {
    success: {
      outPutFriendlyName: 'Information',
      outputDescription: 'TODO: Explain and define the model to return the data'
    },

    infoNotFound: {
      description: 'Could not find the given type of information'
    }  
  },

  fn: function (inputs, exits) {
    var apiURL = sprintf('https://3rdPartySite/v1/%s', inputs.what);
    console.log('Using %s for fetching data from 3rdPartySite', apiURL);

    fetch(apiURL).then( results => {
      return results.json();
    }).then(data => {
      console.log('Info result: %j', data.results);
    });

    // All done.
    return exits.success();
  }
};

But after lifting up that hole thing I get the following displayed in the console:

Uncaught ReferenceError: sails is not defined

I am not able to figure out what I am doing wrong

您无法访问react组件内部的sails对象,因为组件的代码在客户端执行,而sails对象在应用程序的服务器端可全局访问。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM