javascript - 如何使用 React 显示服务器-客户端通信历史记录

标签 javascript reactjs

我构建了这样的东西:

import axios from 'axios';
import React, { Component } from 'react';
class GuessEngine extends Component {
  constructor(props) {
    super(props);

    this.state = {
      number: null,
      result: null,
    };
  }

  componentDidMount() {
    const firstGuess = 5000;
    axios
      .post('http://localhost:3001/number', {
        isNumber: firstGuess,
      })
      .then(response => {
        const { resultCode } = response.data;
        this.setState({ number: firstGuess });
        this.setState({ result: resultCode });
      })
      .catch(error => console.log(error));
  }

  componentDidUpdate() {
    if (this.state.result !== 'success') {
      if (this.state.result === 'lower') {
        const newNumber = this.state.number - 1;
        axios
          .post('http://localhost:3001/number', {
            isNumber: newNumber,
          })
          .then(response => {
            const { resultCode } = response.data;
            this.setState({ result: resultCode, number: newNumber });
          });
      } else if (this.state.result === 'higher') {
        const newNumber = this.state.number + 1;
        axios
          .post('http://localhost:3001/number', {
            isNumber: newNumber,
          })
          .then(response => {
            const { resultCode } = response.data;
            this.setState({ result: resultCode, number: newNumber });
          });
      }
    } else if (this.state.result === 'success') {
      console.log(`Success! The secret number is ${this.state.number}!`);
    } else {
      console.log(`Sorry! Some errors occured!`);
    }
  }

  render() {
    return <div>Test</div>;
  }
}

export default GuessEngine;

我的服务器已生成一个 secret 号码,而我的客户端应用程序正在猜测它。我可以 console.log 每个猜测和结果(较低/较高),但我想知道如何存储每个猜测,然后向用户显示我的所有应用猜测历史记录。

我是否应该将每个猜测写入 this.state.guesses 对象,然后在 render() 方法中映射它以将其显示给用户,或者是这是更好的方法吗?

最佳答案

将条目添加到状态猜测数组中是正确的方法。您应该在使用 setState 之前复制数组。检查 this answer 上的扩展运算符语法:

this.setState({guesses: [...this.state.guesses, newGuess]});

并使用类似的东西来渲染:

{this.state.guesses.map((guess, index) => <div key={index}>{guess}</div>)}

关于javascript - 如何使用 React 显示服务器-客户端通信历史记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49657835/

相关文章:

JavaScript 数组 .reduce 和 async/await

javascript - 无法在 ajax 调用中创建 window.location.reload()

javascript - Reactjs:依赖 render() 函数参数进行渲染不起作用

javascript - 在 react 中按日期对表格进行排序,功能不起作用

javascript - 如何选择 key : value pair in string format used in a JSON object?

javascript - Array.method 和 [].method 的区别

javascript - echo'd PHP 编码通过 AJAX 调用的 JSON 返回什么?

javascript - React中Date方法的ask

reactjs - SetTimeout无限循环并运行一次函数

reactjs - React TypeError : React. renderComponent不是一个函数