首页 > 解决方案 > 在 componentDidMount() 传递要更新的参数的函数内部反应设置状态

问题描述

我需要从 componentDidMount() 中的函数更新组件状态对象元素。理想情况下,我希望能够传递我需要更新的元素和我想要更新它的值。我确实理解“this”是未定义的,并且我已经看到了带有箭头功能的解决方案,但我似乎无法让它工作。

从 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;

标签: javascriptreactjs

解决方案


尝试这个

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

推荐阅读