我构建了这样的东西:
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/