javascript - React 在 componentDidMount() 的函数内设置状态,传递要更新的参数

标签 javascript reactjs

我需要从 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;

最佳答案

试试这个

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

关于javascript - React 在 componentDidMount() 的函数内设置状态,传递要更新的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55229011/

相关文章:

javascript - 为什么 history.go(-1) 在 IE 和 webkit 浏览器中做不同的事情?

javascript - 表单禁用提交按钮,直到选中其子复选框

javascript - 使用 Laravel Passport 时在 React JS 中努力显示验证错误

reactjs - React Hook "useEffect"被有条件地调用。 React Hooks 必须在每个组件渲染中以完全相同的顺序调用

reactjs - ES6 解构对象中的三元条件

javascript - 如何在 React Hooks 中使用 componentWillMount()?

PHP守护进程脚本

java - 编程语言中尾递归的检测

javascript - 如何计算可迭代对象的笛卡尔积

reactjs - react : jsx watch changes compilation directory for react. js