简体   繁体   English

用React猜数字-在这种情况下使用状态的正确方法是什么

[英]Guess the number with React - what is the proper way of using state in that case

My React client app should guess the secret number between 1 and 10 000. Here is my code: 我的React客户端应用程序应该猜测1到10000之间的秘密数字。这是我的代码:

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(prevProps, prevState) {

    if (prevState !== this.state) {
      if (this.state.result === 'lower') {
        const newNumber = this.state.number - 1;
        axios.post('http://localhost:3001/number', {
          isNumber: newNumber,
        });
        this.setState({ number: newNumber });
      }

      if (this.state.result === 'higher') {
        const newNumber = this.state.number + 1;
        axios.post('http://localhost:3001/number', {
          isNumber: newNumber,
        });
        this.setState({ number: newNumber });
      }

      if (this.state.result === 'success') {
        console.log(`Success! The secret number is ${this.state.number}!`);
      }
    }
  }

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

export default GuessEngine;

And I'm getting an error like this: 我收到这样的错误:

Maximum update depth exceeded. 超过最大更新深度。 This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. 当组件重复调用componentWillUpdate或componentDidUpdate内部的setState时,可能会发生这种情况。 React limits the number of nested updates to prevent infinite loops. React限制了嵌套更新的数量,以防止无限循环。

So if I can't use componentDidUpdate like this, what is the proper way to use React Lifecycle Hooks to make it work? 因此,如果我不能像这样使用componentDidUpdate ,那么使用React Lifecycle Hooks使其正常工作的正确方法是什么?

My app has sent 1011 request and than it crashed. 我的应用程序已发送1011请求,然后崩溃了。


SOLUTION

So using @John_Ruddell answer I came up with this solution: 因此,使用@John_Ruddell答案,我想到了以下解决方案:

 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!`);
    }
  }

This code does not compares this.state.number !== prevState.number , but only in this way I forced it to work 这段代码不比较this.state.number !== prevState.number ,但是仅以此方式我强迫它工作

you are setting state every time the component did update is firing.. instead of waiting for a callback from the request to see if its lower or higher 您在每次组件执行更新时都设置状态。.而不是等待请求的回调以查看其较低还是较高

also you should put the logic of state transitions into better conditionals 你也应该把状态转换的逻辑放在更好的条件中

const nextNum = { lower: -1, higher: 1 } // simple mapping of the next guess so you can reduce amount of code
componentDidUpdate(prevProps, prevState) {
    if (this.state.result && this.state.number !== prevState.number) {
        if (nextNum[this.state.result]) {
            // make request with the number
             const newNumber = nextNum[this.state.result]
             axios.post('http://localhost:3001/number', {
                 isNumber: newNumber,
             }).then(response => {
                 const { resultCode } = response.data;
                 this.setState({result: resultCode, number: newNumber})
             }).catch(error => console.log(error));
        } else if (this.state.result === 'success') {
            console.log(`Success! The secret number is ${this.state.number}!`);
        }
    }
}

Note the key thing here is you should only setState AFTER the request comes back.. or else you will just endlessly setState.. because this.state.result will never be updated to be success 请注意,这里的关键是您应该仅在请求返回之后使用setState ..否则,您将无休止地使用setState ..,因为this.state.result将永远不会更新为成功

setState will lead to the update so your componentDidUpdate will be called over and over again: setState将导致更新,因此将一遍又一遍地调用componentDidUpdate

componentDidUpdate(prevProps, prevState) { 
  // after each update this will be true and further runing another updates
  if (prevState !== this.state) {  
  }
}

You need better logic to decipher whether you need to do an update or not. 您需要更好的逻辑来解密是否需要进行更新。 Meaning at some point componentDidUpdate should not do anything. 这意味着componentDidUpdate不应执行任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 React Hooks 设置 state 的正确方法是什么? - What is the proper way to set state with React Hooks? 在React / TypeScript应用程序中初始化可为空状态的正确方法是什么? - What is the proper way of initializing nullable state in React/TypeScript apps? 在React中处理组件状态的正确方法是什么? - What is the proper way to handle component's state in React? 基于 redux 状态控制反应组件的正确方法是什么 - What is the proper way to control react components based on redux state 使用 React Hooks 附加到 React 数组状态的正确方法? - Proper way to append to a React array state using React Hooks? 使用React,呈现具有多个嵌套元素的元素的正确方法是什么? - Using React, what is the proper way to render an element with multiple nested elements? 使用 sass 修改 react-bootstrap 的正确方法是什么? - What's the proper way of modifying react-bootstrap using sass? 使用反应路由器在 url 之间传递参数的正确方法是什么? - What is the proper way to pass parameters between urls using react router? 使用 React 钩子更新动态状态的方法是什么? - What's the way to update dynamic state using React hooks? 使用 React 钩子将数组元素分配给 state 的正确方法是什么? - What is the right way to assign element of an array to state using React hooks?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM