首页 > 解决方案 > React-native ComponentDidMount 未触发

问题描述

每次更改时,我都尝试更新从其他组件导入的声音数组。但是,它只会触发一次 componentDidMount() 并且不会再次运行。下面是我关于这个问题的代码:

//sound array from another component
import { soundArray } from "./CreateRecord";

export default class RecordingList extends React.Component {
constructor() {
super();
this.currentSoundArray = [];
  }

componentDidMount() {
    console.log(this.currentSoundArray);
    this.getCurrentArray();
  }

getCurrentArray() {
    this.currentSoundArray = soundArray;
  }

render(){
...
}

目前,当我查看组件时,componentDidMound 将运行一次并控制声音数组。起初,声音数组是空的:

[]

但是,在我将值放入声音数组并返回查看组件后,它不会打印控制台,也不会更新 this.currentSoundArray 的值

我的预期结果应该是 currentSoundArray 每次在另一个组件中更改 soundArray 时都会更改并打印到控制台。例如:

[]

[1,2]

[1,2,4]

标签: reactjsexpo

解决方案


componentDidMount() 在组件安装后立即调用(插入到树中)。需要 DOM 节点的初始化应该放在这里。如果您需要从远程端点加载数据,这是实例化网络请求的好地方。

它只运行一次。


推荐阅读