简体   繁体   English

当 window 变量在反应中发生变化时,如何更新 state

[英]How do I update state when a window variable changes in react

I have a fairly simple class component that needs access to some data from a service written in vanilla JS.我有一个相当简单的 class 组件,它需要从用 vanilla JS 编写的服务访问一些数据。 It's simply an interface for the Web MIDI API, that must get access to the MIDI ports, then triggers a callback.它只是 Web MIDI API 的接口,必须访问 MIDI 端口,然后触发回调。 I'm importing a function setMidiPorts to the MIDI service then calling it and sending the list of ports on MIDI success.我正在将 function setMidiPorts 导入 MIDI 服务,然后调用它并在 MIDI 成功时发送端口列表。 I then need to render those ports in a drop down, but can't seem to get them updated in the component.然后我需要在下拉列表中呈现这些端口,但似乎无法在组件中更新它们。 I've tried passing them down as props from the parent, I've tried importing them directly.我尝试将它们作为来自父母的道具传递下来,我尝试直接导入它们。 Nothing seems to work.似乎没有任何效果。 I'm pretty new to react so I'm probably doing something pretty wrong, can anyone help me by pointing out where I'm going wrong.我对反应很陌生,所以我可能做错了什么,任何人都可以通过指出我哪里出错来帮助我。

window.inputs = [];

export const setMidiPorts = (inputs) => {
  window.inputs = inputs;
  console.log(inputs);
};

export default class Preferences extends Component {
  constructor(props) {
    super(props);
    this.state = {
      midiInputs: window.inputs,
      midiOutputs: [],
    };
  }
......

EDIT -编辑 -

I'm looking at this question to see if I can update state from outside, but don't understand how it works properly.我正在查看这个问题,看看我是否可以从外部更新 state,但不明白它是如何正常工作的。

Update component state from outside React (on server response) 从 React 外部更新组件 state(在服务器响应上)

Thanks for everyones advice, I managed to solve it by following what it says here.感谢大家的建议,我设法按照这里所说的来解决它。

https://brettdewoody.com/accessing-component-methods-and-state-from-outside-react/ https://brettdewoody.com/accessing-component-methods-and-state-from-outside-react/

Adding this inside the component render在组件渲染中添加这个

ref={(Preferences) => {window.Preferences = Preferences;}}

Then I was able to define the setMidiPorts function inside the component and call it from anywhere with window.Preferences.setMidiPorts然后我能够在组件内部定义 setMidiPorts function 并使用window.Preferences.setMidiPorts从任何地方调用它

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

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