简体   繁体   English

如何导出componentDidMount的变量(react / react-native)

[英]How can I export variables of componentDidMount ( react/react-native)

How to export variable in class? 如何在课堂上导出变量? Do I need Rudux? 我需要Rudux吗? I want to use 我想用

import device_token from './xxx';

below is my previous code. 下面是我以前的代码。

global.device_token = token 

However, I don't like global variables. 但是,我不喜欢全局变量。

I just export Stnig variable, which is device_token. 我只是导出Stnig变量,它是device_token。 I must not change the devce_token, because, device_token is user's device's name. 我不能更改devce_token,因为device_token是用户设备的名称。 So I don't want to use redux. 所以我不想使用redux。 redux state is changeable. redux状态是可变的。 I need an immutable variable. 我需要一个不变的变量。 and import the variable. 并导入变量。

export class PushNotification extends Component {
  componentDidMount() {
    SomeAPI.then((token: string) => {
     const device_token = token
  });

  ....
}

Do you have any idea? 你有什么主意吗? thanks. 谢谢。

It seems like you want access to device_token in other React components. 似乎您想访问其他React组件中的device_token If that is the case, then Redux would work because it would provide a centralized state that all components can draw from. 如果真是这样,那么Redux就可以工作了,因为它将提供所有组件都可以借鉴的集中状态。 I suggest using Redux to store/modify device_token , something like: 我建议使用Redux来存储/修改device_token ,类似于:

export class PushNotification extends Component {
  componentDidMount() {
    SomeAPI.then((token: string) => {
      this.props.setDeviceToken(token);
    });

....
}

Where setDeviceToken dispatches an action creator that is passed in through a container. setDeviceToken调度通过容器传入的操作创建者。

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

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