简体   繁体   English

在React.js中更新导入的变量的值

[英]Updating my imported variable's value in React.js

I am refractoring an app I've build using React.js. 我正在使用React.js构建一个应用程序。 I am exporting a variable from the global scope of Spotify.js and importing it in two other files App.js and Button.js . 我正在从Spotify.js的全局范围导出变量,并将其导入另外两个文件App.jsButton.js After calling a function from Spotify.js that sotres a new value to the variable, It's new value is exported to 'Button.js' but stays an empty string in 'App.js'. Spotify.js调用将变量添加一个新值的函数后,该新值将导​​出到“ Button.js”,但在“ App.js”中保留一个空字符串。

Your help would be appriciated :) 您的帮助将不胜感激:)


export let userAccessToken = '';
export const Spotify = {
  ...
  getUserAccessToken (){
    //stores a new string to userAccessToken.
    }
  }
  import {userAccessToken, Spotify} from '../../util/Spotify';

  export class App extends React.Component {
    //a conditional rendering happens depending on if(!userAccessToken)
  }
  import {userAccessToken, Spotify} from '../../util/Spotify'

  export class Button extends React.Component {

      componentDidMount() {

      if (!userAccessToken) {

        console.log(`Button's UAT before calling the fn: ${userAccessToken}`)
        Spotify.getUserAccessToken();
        console.log(`Button's UAT after calling the fn: ${userAccessToken}`);

      } 
    }

  ...

  }

This is not how you share data between react components. 这不是您在React组件之间共享数据的方式。

Use react context or pass props between components 在组件之间使用反应上下文或传递道具

You could use react context to share data or simply pass it as props (if the components are closely related in the component tree) 您可以使用react上下文共享数据,也可以简单地将其作为道具传递(如果组件在组件树中紧密相关)

The only thing I can recommend is to export the userAccessToken, something like this, but you can't change its value outside the module 我唯一推荐的方法是导出userAccessToken,类似这样,但是您不能在模块外部更改其值

export const Spotify = {
  ...
  getUserAccessToken (){
    //stores a new string to userAccessToken.
    }
  }
  ...
}

const accessToken = Spotify.getUserAccessToken();
export const userAccessToken = accessToken;

If you got to read this question I solved it. 如果您要阅读此问题,则可以解决。 Turns out I should have called my method Spotify.getUserAccessToken() from App.js using the react lifecycle method componentDidMount() . 事实证明,我应该已经使用App.js生命周期方法componentDidMount()App.js调用了我的方法Spotify.getUserAccessToken() componentDidMount() The export and import methods are like snapshots of the module and therefore when I exported the variable userAccessToke from Spotify.js before calling the my method I imported an empty string and it did not update in all files. 导出和导入方法就像模块的快照一样,因此,当我在调用my方法之前从Spotify.js导出变量userAccessToke ,我导入了一个空字符串,并且它并未在所有文件中更新。

Thanks Jørgen and joseluismurillorios for your support and time spent answering :) 感谢Jørgen和joseluismurillorios的支持以及您在回答问题上所花费的时间:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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