如何在React的监听器期间更新数组元素的状态?



我正在开发一个web应用程序,通过socket.io读取传感器数据来测量对象。

addNewGauge()函数将一个元素添加到组件的量规数组中,但是我还想安装一个插座。元素的IO监听器。

addNewGauge()函数工作,并且侦听器正在拾取事件,我知道这是因为每个套接字事件都会发生以下错误:

TypeError: Cannot read property 'value' of undefined

我假设这是因为它不能在监听器期间读取数组索引?如何在每次状态中更新特定元素的状态?

import React from 'react'
import socketIOClient from "socket.io-client"
class WidgetContainer extends React.Component {
constructor(props) {
super(props)
this.state = {
//Initial array of gauges
gauges: [{
index: 0,
sensorType: 'temperature',
units: "Fahrenheit"
}],
//Endpoint for socket data
endpoint: 'http://127.0.0.1:4200'
}
this.addNewGauge = this.addNewGauge.bind(this)
}
componentDidMount() {
const {endpoint} = this.state;
//Fire up the socket when container is mounted
this.widget_socket = socketIOClient(endpoint)
}
addNewGauge() {
this.setState(state => {
// ensure next gauge has a unique index
const nextIndex = state.gauges.length;
const gaugeList = state.gauges.concat({
index: nextIndex,
sensorType: 'temperature',
units: "Fahrenheit"
});
// Set up a listener for that gauge's sensor type
//BROKEN
this.widget_socket.on(gaugeList[nextIndex].sensorType, (data) => {
//Update state with new sensor value
let newState = update(this.state.gauges, {
nextIndex: {
value: {
$set: data
}
}
})
this.setState(newState);
})
return {
gauges: gaugeList
};
});
}
render() {
let gaugeList = this.state.gauges.map((gauge) =>
<Gauge 
key = {gauge.index}
// Specify gauge properties from our saved state
value = {gauge.value}
units = {gauge.units}
/>
);
return ( 
<div>
{gaugeList}
<Button key="addButton" 
onClick={this.addNewGauge}
>Add gauge</Button>
</div>
);
}
}
export default WidgetContainer

我似乎找到了一个解决方案

  1. 添加一个单独的回调和绑定到类
  2. 未使用"update()">

当状态被修改时,这个套接字的回调工作得很好:

let widgetCallback = (data, index) => {
let newState = this.state
newState.gauges[index].value = data;
this.setState(newState)
}
// bind the callback to the container
widgetCallback.bind(this)

最新更新