【问题标题】:React count array in API and reset / start again在 API 中反应计数数组并重新设置/重新启动
【发布时间】:2018-08-18 21:09:55
【问题描述】:

大家好,我一直在尝试在 React 中创建一个使用工作人员 API 的 Rota,这是我一直在使用的代码。目前,它读取数组,然后每 3 秒向状态添加一个随机数。

我想要它做的是从 0 计数到数组的值,然后重置。有任何想法吗?

import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
import { once, every, daily } from 'bella-scheduler';

class App extends Component {
  constructor(props) {
      super(props);
      this.state = {
          data: [0]
      }
  }

  componentDidMount() {
      axios.get('http://localhost:3333/staff')
      .then((response) => {
          this.successShow(response);
      })
      .catch((error) => {
          this.successShow('error');
      });
  }


  successShow(response) {
        console.log(response.data);

        every('3s', () => {

            var i = Math.floor(Math.random()*(response.data.length))
            this.setState({person: response.data[i].name});
            console.log('Resolved task.');

        });

    }


  render() {
      return (
          <div className="main">
            <h2 className="title">Rota</h2>
            <h3>{this.state.person}</h3>
          </div>
      );
  }
}


export default App;

【问题讨论】:

    标签: arrays reactjs api math state


    【解决方案1】:

    您必须添加一个计数器而不是 random() 索引器来显示彼此的名称。

    所以在你的状态中添加一个 cnt 或 counter 变量,然后每 3 秒增加一次数字,但将其与 % 一起使用,如下所示以防止索引问题。

    对于构造函数:

    constructor(props) {
          super(props);
          this.state = {
              data: [0],
              cnt:0
          }
      }
    

    对于successShow函数:

    successShow(response) {
            console.log(response.data);
    
            every('3s', () => {
    
                var i = this.state.cnt++;
                this.setState({person: response.data[i%response.data.lenght].name});
                console.log('Resolved task.');
    
            });
    
        }
    

    【讨论】:

    • 谢谢你,我已经添加了这个,但我收到错误“无法读取未定义的属性'名称'”我更改了“var i = this,state.cnt++;”到“var i = response.data.length.cnt++;”但随后出现无法在数字 '5' 上创建属性 'cnt' 的错误,原因是该对象确实有 5 个值,但它的计数范围是 0 - 4 而不是 1 - 5
    • 一切都是最新的,但您必须在构造函数中初始化参数 cnt 的第一个值。我添加了构造函数更改。
    • 非常感谢!我现在可以在您的 cmets 中使用它,但上面的长度有一个错字。你有支持这种方法的链接吗?所以我知道下次去哪里看?
    • 这些是算法技巧,你必须理解上面例子的%。看看这个:w3schools.com/js/js_arithmetic.asp
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多