Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

javascript - 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. It's simply an interface for the Web MIDI API, that must get access to the MIDI ports, then triggers a callback. I'm importing a function setMidiPorts to the MIDI service then calling it and sending the list of ports on MIDI success. 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.

Update component state from outside React (on server response)

question from:https://stackoverflow.com/questions/65860354/how-do-i-update-state-when-a-window-variable-changes-in-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...