首页 > 解决方案 > 如何从 React 组件的根文件夹中的 JS 文件中读取变量?

问题描述

我想从公用文件夹中的 notification.js 访问“testmsg”变量。

这是我的 notification.js 代码:

let testmsg = "abc";
self.addEventListener('push', event => {
  console.log(self);
  console.log(event);
  const data = event.data.json();
  testmsg = data;
  console.log(testmsg);
  console.log('New notification', data);
  console.log(data.body);
  const options = {
    body: data.body,
  }
  event.waitUntil(
    self.registration.showNotification(data.title, options)
  );
})

这是我的 App.js

import React from 'react';
import axios from 'axios';
import uuid from 'uuid/v4';
import requestIp from 'ip';
import Message from './Message';
import * as testmsgtemp from '../public/notification.js';

class App extends React.Component {

    constructor(props){
        super(props);
        this.myRef = React.createRef();
        this.state = { resp: '', correlationId: '', name: '', correlationIdRes: '', nameRes: '' };
    }

    WriteDataToKafka = async () => {
        console.log(requestIp.address());
        this.setState({ correlationId: uuid() });
        console.log(this.state.name);
        setTimeout(async function () {
            console.log(this.state.correlationId);
            await axios.get(<service URL>, {
                headers: {
                    uuid: this.state.correlationId,
                    deviceid: Message.getP256dh(),
                    auth: Message.getAuth(),
                    endpoint: Message.getEndpoint(),
                    ipAddress: requestIp.address()
                },
                params: {
                    parameter: this.state.name
                }
            });
        }.bind(this), 50);

        setTimeout(function () {
        console.log("variable:::",testmsgtemp.testmsg);
        }, 600);
    }

     /* eslint-disable */
    componentDidMount(){
        navigator.serviceWorker.register("./notfications.js").then(function(registration){
            console.log(registration);
        });
    }

    render() {
         return (

        <div  ref={this.myRef}>
            <input placeholder="Enter Your Name" onChange={(e) => this.setState({name: e.target.value})}></input>
            <br/><br/>
            <button onClick={this.WriteDataToKafka}>Call Service</button>
            <p>Hej {this.state.nameRes}!</p>
            <p> Unique ID Generated is: {this.state.correlationId}</p>
            <p> Unique ID Received is: {this.state.correlationIdRes}</p>

        </div>);
    }
}

export default App;

请指导我如何读取 App.js 中的 testmsg 变量。我还运行npm eject将 notification.js 从根文件夹导入 src。如果可以在 App.js 中读取 testmsg 变量值,那么我可以使用它在 DOM 中呈现它。我正在尝试开发一种实用程序,该实用程序无需客户端请求即可将数据推送到客户端。

标签: javascriptreactjspush-notification

解决方案


我希望我没有误解您要实现的目标,但我会尽力而为,如果您的意思是要访问位于 src 文件夹上方的公用文件夹,该文件夹实际上用于您的浏览器下载公共信息,例如您的ico 文件、徽标等,以及在 react 之外的 index.js/app.js 文件夹之外可以访问。不过不用担心,总会有其他方法。您可以在 src 中创建另一个数据文件并访问它,然后构建到包中。

如果你想实现更小的构建包,你可以使用带有 react.lazy() 的代码拆分。webpack 会将捆绑包分成几个以减小尺寸(下载速度更快)

如果它不是您的意思的 src 文件夹上方的公用文件夹......那么您可以简单地进行导入/导出:

例如:

通知.js 代码:

export default testmsg = "abc";

在你的 App.js

import testmsg from '../public/notification.js';

或者

const testmsg = 'abc'
const exportObject = {testmsg}
export default exportObject;

然后在你的 App.js 中

import {testmsg} from '../public/notification.js';

然后只需使用console.log(testmsg); //abc


推荐阅读