[英]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请求,然后崩溃了。
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.