简体   繁体   English

在componentDidMount()上传递要更新的参数的函数内部的设置状态做出反应

[英]React setting state inside function on componentDidMount() passing parameters to be updated

I need to update component state object elements from function inside componentDidMount(). 我需要从componentDidMount()中的函数更新组件状态对象元素。 Ideally I want to be able to pass the element I need to update and the value I want to update it with. 理想情况下,我希望能够传递我需要更新的元素以及我想用来更新它的值。 I do understand "this" is undefined and I have seen solutions with arrow functions but I can't seem to get it to work. 我确实知道“ this”是未定义的,并且我已经看到了带有箭头功能的解决方案,但是我似乎无法使其正常工作。

What would be the best approach to update state from function inside componentDidMount() passing element and value to be updated? 从componentDidMount()内部的函数传递要更新的元素和值的状态来更新状态的最佳方法是什么?

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      obj: {
        itemone: "on",
        itemtwo: "off"
      }
    };
  }

  // updateState(item, valStr) {
  //   this.setState({
  //       obj: {
  //         item: valStr
  //       }
  //   });
  // };

  componentDidMount() { 
      //.......
      websocket.onmessage = function (event) {
        //this.updateState(itemone "off");
        this.setState({ //undefined
            obj: {
              itemone: "off"
            }
        });
      };
  }

  render() {

    return (
      <div className="App">
        ...
      </div>
    );
  }
}

export default App;

try this 尝试这个

websocket.onmessage = (function (event) {
        //this.updateState(itemone "off");
        this.setState({
            obj: {
              itemone: "off"
            }
        });
}).bind(this);

Given your inability to use arrow functions, you can circumvent the this coming undefined by: 鉴于你无法使用箭头功能,可以规避this未来不确定的是:

componentDidMount() { 

// Define a variable pointing to the `this` of the class
const newThis = this
websocket.onmessage = function (event) {
   // Use that this to call the setState
   newThis.setState(prevState => {
      const newObj = prevState.obj
      newObj.itemone = "off"
      return { obj: newObj}
   })
  }
}

You can try the arrow function 您可以尝试arrow function

websocket.onmessage = (event) => {
    //this.updateState(itemone "off");
    this.setState({ //undefined
        obj: {
          itemone: "off"
        }
    });
  };

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

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