我建造了这样的东西:
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;
我的服务器生成了一个密码,而我的客户端应用程序正在猜测它。我可以console.log每次猜测和结果(更低/更高),但我想知道如何存储每个猜测,然后向用户显示我的所有应用程序猜测历史记录。
我应该将每个猜测写入this.state.guesses
对象,然后在render()
方法中我应该将其映射到用户,还是更好的方式?
答案 0 :(得分:1)
在状态上向猜测数组添加条目是正确的方法。你应该在使用setState之前复制数组。检查this answer上的传播运算符语法:
this.setState({guesses: [...this.state.guesses, newGuess]});
使用这样的东西来渲染:
{this.state.guesses.map((guess, index) => <div key={index}>{guess}</div>)}