使用字典设置状态在 REACT 中不起作用
Setting state with dictionnary not working in REACT
我目前正在学习REACT,但我对状态仍有一些问题。
好像我不能用字典设置状态。
class Game extends React.Component {
state = {
selectedCharacters: [{"name":"Loup Garou","imgName":"base_loup.png","uniqueKey":"loup","playerName":""},{"uniqueKey":"voyante","imgName":"base_voyante.png","name":"Voyante","maxInGame":1,"left":1}],
turnList: [],
gameStatus: "characterSelection",
};
saveStateToStorage() {
localStorage.setItem("gameState", JSON.stringify(this.state));
}
startGame = () => {
//Démarre la partie
var turns = this.createTurnListFromSelectedCharacters();
console.log(turns);
this.setState({
turnList: turns,
gameStatus: "gameStarted",
},
() => {
//Sauvegarde l'état du jeu dans le local storage
this.saveStateToStorage();
console.log(this.state.turnList);
}
);
};
createTurnListFromSelectedCharacters = () => {
//Création de la liste des tours ainsi que du compteur de joueur en vie
var turns = [];
for (var i = 0; i < this.state.selectedCharacters.length; i++)
{
var char = this.state.selectedCharacters[i];
var turn = turns[char.uniqueKey];
if (turn === undefined) {
var namesList = [{ name: char.playerName, isAlive: true }];
var newTurn = {
charKey: char.uniqueKey,
alive: 1,
inGame: 1,
names: namesList,
imgName: char.imgName
};
turns[char.uniqueKey] = newTurn;
}
else {
turn.names.push({ name: char.playerName, isAlive: true });
turn.alive = turn.alive + 1;
turn.inGame = turn.inGame + 1;
turns[char.uniqueKey] = turn;
}
}
return turns;
};
render() {...}
}
第一个 console.log 显示由我的函数 createTurnListFromSelectedCharacters 正确生成的字典,setState 回调中的第二个 console.log 不显示任何内容。
如果我在 setState 中放入类似 'turnList: [1,2,3,4,5]' 或任何数组的内容,它就可以工作。
您需要在构造方法中设置状态,例如:
class Game extends React.Component {
constructor(props){
super(props);
this.state = {
selectedCharacters: [{ "name": "Loup Garou", "imgName": "base_loup.png", "uniqueKey": "loup", "playerName": "" }, { "uniqueKey": "voyante", "imgName": "base_voyante.png", "name": "Voyante", "maxInGame": 1, "left": 1 }],
turnList: [],
gameStatus: "characterSelection",
};
}
...
}
您使用的是数组 []
,而不是字典的对象。请改用常规对象。
class Game extends React.Component {
state = {
selectedCharacters: [{ "name": "Loup Garou", "imgName": "base_loup.png", "uniqueKey": "loup", "playerName": "" }, { "uniqueKey": "voyante", "imgName": "base_voyante.png", "name": "Voyante", "maxInGame": 1, "left": 1 }],
turnList: {},
gameStatus: "characterSelection",
};
componentDidMount() {
this.startGame();
}
saveStateToStorage() {
localStorage.setItem("gameState", JSON.stringify(this.state));
}
startGame = () => {
//Démarre la partie
var turns = this.createTurnListFromSelectedCharacters();
console.log("foo", turns);
this.setState({
turnList: turns,
gameStatus: "gameStarted",
},
() => {
//Sauvegarde l'état du jeu dans le local storage
this.saveStateToStorage();
console.log(this.state.turnList);
}
);
};
createTurnListFromSelectedCharacters = () => {
//Création de la liste des tours ainsi que du compteur de joueur en vie
var turns = {};
for (var i = 0; i < this.state.selectedCharacters.length; i++) {
var char = this.state.selectedCharacters[i];
console.log( char.uniqueKey );
var turn = turns[char.uniqueKey];
if (turn === undefined) {
var namesList = [{ name: char.playerName, isAlive: true }];
var newTurn = {
charKey: char.uniqueKey,
alive: 1,
inGame: 1,
names: namesList,
imgName: char.imgName
};
turns[char.uniqueKey] = newTurn;
}
else {
turn.names.push({ name: char.playerName, isAlive: true });
turn.alive = turn.alive + 1;
turn.inGame = turn.inGame + 1;
turns[char.uniqueKey] = turn;
}
}
return turns;
};
render() {
const { turnList } = this.state;
return (
<div>{
Object.keys(turnList).map( key => (
<div key={turnList[ key ].charKey}>
<p>Charkey: {turnList[ key ].charKey}</p>
<p>Alive: {turnList[ key ].alive}</p>
</div>
))
}</div>
);
}
}
ReactDOM.render(<Game />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
如果我将 devserkan 的回答与我在另一个主题上找到的内容结合起来。
我明白了:
class Game extends React.Component {
state = {
selectedCharacters: [{ "name": "Loup Garou", "imgName": "base_loup.png", "uniqueKey": "loup", "playerName": "" }, { "uniqueKey": "voyante", "imgName": "base_voyante.png", "name": "Voyante", "maxInGame": 1, "left": 1 }],
turnList: {},
gameStatus: "characterSelection",
};
startGame = () => {
//Démarre la partie
var turns = this.createTurnListFromSelectedCharacters();
console.log("foo", turns);
this.setState({
turnList: turns,
gameStatus: "gameStarted",
},
() => {
//Sauvegarde l'état du jeu dans le local storage
this.saveStateToStorage();
console.log(this.state.turnList);
}
);
};
createTurnListFromSelectedCharacters = () => {
//Création de la liste des tours ainsi que du compteur de joueur en vie
var turns = {};
for (var i = 0; i < this.state.selectedCharacters.length; i++) {
var char = this.state.selectedCharacters[i];
console.log( char.uniqueKey );
var turn = turns[char.uniqueKey];
if (turn === undefined) {
var namesList = [{ name: char.playerName, isAlive: true }];
var newTurn = {
charKey: char.uniqueKey,
alive: 1,
inGame: 1,
names: namesList,
imgName: char.imgName
};
turns[char.uniqueKey] = newTurn;
}
else {
turn.names.push({ name: char.playerName, isAlive: true });
turn.alive = turn.alive + 1;
turn.inGame = turn.inGame + 1;
turns[char.uniqueKey] = turn;
}
}
return turns;
};
render() {
return (
<div>
{Object.keys(props.aliveCount).map((turn, i) => {
return (
<div>
<img alt={props.aliveCount[turn].imgName} src= {require("../../public/images/" + props.aliveCount[turn].imgName)} />
{props.aliveCount[turn].alive}/{props.aliveCount[turn].inGame}
</div>
);
})}
</div>
);
}
}
我需要使用 {} 设置我的对象,然后用户 Object.keys 来映射它。
我目前正在学习REACT,但我对状态仍有一些问题。 好像我不能用字典设置状态。
class Game extends React.Component {
state = {
selectedCharacters: [{"name":"Loup Garou","imgName":"base_loup.png","uniqueKey":"loup","playerName":""},{"uniqueKey":"voyante","imgName":"base_voyante.png","name":"Voyante","maxInGame":1,"left":1}],
turnList: [],
gameStatus: "characterSelection",
};
saveStateToStorage() {
localStorage.setItem("gameState", JSON.stringify(this.state));
}
startGame = () => {
//Démarre la partie
var turns = this.createTurnListFromSelectedCharacters();
console.log(turns);
this.setState({
turnList: turns,
gameStatus: "gameStarted",
},
() => {
//Sauvegarde l'état du jeu dans le local storage
this.saveStateToStorage();
console.log(this.state.turnList);
}
);
};
createTurnListFromSelectedCharacters = () => {
//Création de la liste des tours ainsi que du compteur de joueur en vie
var turns = [];
for (var i = 0; i < this.state.selectedCharacters.length; i++)
{
var char = this.state.selectedCharacters[i];
var turn = turns[char.uniqueKey];
if (turn === undefined) {
var namesList = [{ name: char.playerName, isAlive: true }];
var newTurn = {
charKey: char.uniqueKey,
alive: 1,
inGame: 1,
names: namesList,
imgName: char.imgName
};
turns[char.uniqueKey] = newTurn;
}
else {
turn.names.push({ name: char.playerName, isAlive: true });
turn.alive = turn.alive + 1;
turn.inGame = turn.inGame + 1;
turns[char.uniqueKey] = turn;
}
}
return turns;
};
render() {...}
}
第一个 console.log 显示由我的函数 createTurnListFromSelectedCharacters 正确生成的字典,setState 回调中的第二个 console.log 不显示任何内容。 如果我在 setState 中放入类似 'turnList: [1,2,3,4,5]' 或任何数组的内容,它就可以工作。
您需要在构造方法中设置状态,例如:
class Game extends React.Component {
constructor(props){
super(props);
this.state = {
selectedCharacters: [{ "name": "Loup Garou", "imgName": "base_loup.png", "uniqueKey": "loup", "playerName": "" }, { "uniqueKey": "voyante", "imgName": "base_voyante.png", "name": "Voyante", "maxInGame": 1, "left": 1 }],
turnList: [],
gameStatus: "characterSelection",
};
}
...
}
您使用的是数组 []
,而不是字典的对象。请改用常规对象。
class Game extends React.Component {
state = {
selectedCharacters: [{ "name": "Loup Garou", "imgName": "base_loup.png", "uniqueKey": "loup", "playerName": "" }, { "uniqueKey": "voyante", "imgName": "base_voyante.png", "name": "Voyante", "maxInGame": 1, "left": 1 }],
turnList: {},
gameStatus: "characterSelection",
};
componentDidMount() {
this.startGame();
}
saveStateToStorage() {
localStorage.setItem("gameState", JSON.stringify(this.state));
}
startGame = () => {
//Démarre la partie
var turns = this.createTurnListFromSelectedCharacters();
console.log("foo", turns);
this.setState({
turnList: turns,
gameStatus: "gameStarted",
},
() => {
//Sauvegarde l'état du jeu dans le local storage
this.saveStateToStorage();
console.log(this.state.turnList);
}
);
};
createTurnListFromSelectedCharacters = () => {
//Création de la liste des tours ainsi que du compteur de joueur en vie
var turns = {};
for (var i = 0; i < this.state.selectedCharacters.length; i++) {
var char = this.state.selectedCharacters[i];
console.log( char.uniqueKey );
var turn = turns[char.uniqueKey];
if (turn === undefined) {
var namesList = [{ name: char.playerName, isAlive: true }];
var newTurn = {
charKey: char.uniqueKey,
alive: 1,
inGame: 1,
names: namesList,
imgName: char.imgName
};
turns[char.uniqueKey] = newTurn;
}
else {
turn.names.push({ name: char.playerName, isAlive: true });
turn.alive = turn.alive + 1;
turn.inGame = turn.inGame + 1;
turns[char.uniqueKey] = turn;
}
}
return turns;
};
render() {
const { turnList } = this.state;
return (
<div>{
Object.keys(turnList).map( key => (
<div key={turnList[ key ].charKey}>
<p>Charkey: {turnList[ key ].charKey}</p>
<p>Alive: {turnList[ key ].alive}</p>
</div>
))
}</div>
);
}
}
ReactDOM.render(<Game />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
如果我将 devserkan 的回答与我在另一个主题上找到的内容结合起来。 我明白了:
class Game extends React.Component {
state = {
selectedCharacters: [{ "name": "Loup Garou", "imgName": "base_loup.png", "uniqueKey": "loup", "playerName": "" }, { "uniqueKey": "voyante", "imgName": "base_voyante.png", "name": "Voyante", "maxInGame": 1, "left": 1 }],
turnList: {},
gameStatus: "characterSelection",
};
startGame = () => {
//Démarre la partie
var turns = this.createTurnListFromSelectedCharacters();
console.log("foo", turns);
this.setState({
turnList: turns,
gameStatus: "gameStarted",
},
() => {
//Sauvegarde l'état du jeu dans le local storage
this.saveStateToStorage();
console.log(this.state.turnList);
}
);
};
createTurnListFromSelectedCharacters = () => {
//Création de la liste des tours ainsi que du compteur de joueur en vie
var turns = {};
for (var i = 0; i < this.state.selectedCharacters.length; i++) {
var char = this.state.selectedCharacters[i];
console.log( char.uniqueKey );
var turn = turns[char.uniqueKey];
if (turn === undefined) {
var namesList = [{ name: char.playerName, isAlive: true }];
var newTurn = {
charKey: char.uniqueKey,
alive: 1,
inGame: 1,
names: namesList,
imgName: char.imgName
};
turns[char.uniqueKey] = newTurn;
}
else {
turn.names.push({ name: char.playerName, isAlive: true });
turn.alive = turn.alive + 1;
turn.inGame = turn.inGame + 1;
turns[char.uniqueKey] = turn;
}
}
return turns;
};
render() {
return (
<div>
{Object.keys(props.aliveCount).map((turn, i) => {
return (
<div>
<img alt={props.aliveCount[turn].imgName} src= {require("../../public/images/" + props.aliveCount[turn].imgName)} />
{props.aliveCount[turn].alive}/{props.aliveCount[turn].inGame}
</div>
);
})}
</div>
);
}
}
我需要使用 {} 设置我的对象,然后用户 Object.keys 来映射它。