【问题标题】:Handling state react native处理状态反应原生
【发布时间】:2020-05-13 04:29:59
【问题描述】:

这是我的带有 linechart(LChart) 组件的选择器。

<Picker selectedValue = {this.state.value}
          onValueChange = {this.onValueChange}
          >
          <Picker.Item value='' label='Select Device...' />
          {devices.map((s, i) => {
            return (<Picker.Item label={s} value={s} key={i}/>)
        })}
            </Picker>

        <LChart data={Fdata} title={"LineChart"}/>

我有一组设备要输入选择器,并且每次 onValuechange 我都想显示相应设备的折线图。 我的 onValueChange 函数:

onValueChange = async(value) => {
      this.setState({ value: value })
      this.interval = setInterval(() => {
      var Fdata = [];
      fetch('http://ec2-137.compute-1.amazonaws.com:3009/chart/unitID', {
        method: 'post',
        headers:{
          'Accept': 'application/json',
          'Content-type': 'application/json'
        },
        body:JSON.stringify({
          unitID: value,
        }) })
      .then((response) => response.json())
        .then((responseJson) => {
          responseJson.forEach(function (vol) {
            Fdata.push({
              value: vol.voltage,
              date: new Date(vol.time),
            });
          });
          if (this._isMounted) {
            this.setState({
                Fdata: Fdata,
            });
          }
        })
      }, 5000);
   }

我的问题是当我最初从选择器中选择一个设备时,折线图显示完美,并根据我设置的间隔重新加载。 但是当我从选择器中选择一个不同的设备时,折线图开始在第一个和第二个设备数据之间切换,同样继续第三个选择,依此类推。

我想我没有正确处理状态。 任何帮助将不胜感激。非常感谢。

【问题讨论】:

  • 您没有清除创建的间隔。
  • @zero298 我刚刚做了这个,它工作正常` clearInterval(this.interval); this.interval = setInterval(() => { `

标签: reactjs react-native charts state setstate


【解决方案1】:

您需要清理间隔。现在,您只需继续创建额外的间隔来 ping 设备。您可以做的一件事是创建一个useEffect,它将在所选设备更改后清除间隔。下面的示例使用了占位符,但您应该能够看到大致的想法。

const {useState, useEffect, Fragment} = React;

const Chart = ({deviceData}) => {
    return (
        <div>
            {deviceData ? (
                <Fragment>
                    <div>Date fetched: {Date.now()}</div>
                    <pre><code>{JSON.stringify(deviceData, null, 4)}</code></pre>
                </Fragment>
            ) : (
                <p>Waiting for device</p>
            )}
        </div>
    );
};

const App = () => {
    const [selectedDevice, setSelectedDevice] = useState("");
    const [deviceAttrs, setDeviceAttrs] = useState();

    useEffect(() => {
        if (!selectedDevice) return;
        const interval = setInterval(() => {
            fetch(`http://jsonplaceholder.typicode.com/todos/${selectedDevice}`)
            .then(res => res.json())
            .then(data => setDeviceAttrs(data));
        }, 5000);

        return () => clearInterval(interval);
    }, [selectedDevice]);

    const options = [1, 2, 3];

    return (
        <div>
            <select onChange={e => setSelectedDevice(e.target.value)}>
                <option value="">Please select a device</option>
                {options.map(option => (
                    <option key={option} value={option}>Device {option}</option>
                ))}
            </select>
            {selectedDevice ? (
                <Chart deviceData={deviceAttrs} />
            ) : (
                <div>Please select a device</div>
            )}
        </div>
    );
};

ReactDOM.render(<App />, document.getElementById("app"));
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>

<div id="app"></div>

【讨论】:

  • 非常感谢。这真的很有帮助
猜你喜欢
  • 2021-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多