反应本机ComponentDidMount不触发

时间:2019-10-14 12:19:53

标签: reactjs expo

每次更改时,我都尝试更新从其他组件导入的声音阵列。但是,它只会触发一次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]

2 个答案:

答案 0 :(得分:1)

  

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

它只能运行一次。

答案 1 :(得分:0)

您要尝试的是访问currentSoundArray值(从其他组件更新后的值),因为您传统上将无法执行此操作。

componentDidMount仅在首次初始化和呈现组件时仅触发一次。

解决方案1 ​​

一种更好的方法是使用React Redux之类的方法来管理应用程序状态,这样您就可以从整个应用程序中的任何组件访问状态。

如果您想在Github上查看它,我已经完成了针对此模板的样板模板设置:)

解决方案2

如果您对Redux不感兴趣,那么我建议您为此使用react context,它也会解决您的问题。您可以在线查看许多示例,例如this使用上下文在各个组件之间共享小吃店。

希望这会有所帮助!

相关问题