gpt4 book ai didi

javascript - 为什么我不能使用 setState 将对象传递给状态?

转载 作者:行者123 更新时间:2023-11-30 09:26:03 25 4
gpt4 key购买 nike

在过去的 2 个小时里,我一直盯着同一段代码看,不明白为什么我在 onReveal() 方法中的 setState 没有更新构造函数的状态。我已经检查过,我似乎确实在创建一个有效的对象 (revealedArray),但无论我做什么,这似乎都没有传递给状态。

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import './App.css';

const Card = (props) => {
return <div
key={props.id}
className="Card"
style={props.cardState===CardState.hidden ? {backgroundColor: "dimGrey"} : {backgroundColor: props.colour}}
onClick={() => {props.onReveal(props.id)}}
>
Hello from {props.colour} Card number {props.id}. cardState is {props.cardState}
</div>;
}

Card.propTypes = {
onReveal: PropTypes.func.isRequired,
};

class CardHolder extends Component {
static propTypes = {
cards: PropTypes.arrayOf(PropTypes.object).isRequired,
}
render() {
const {onReveal} = this.props;
const AllCards = this.props.cards.map((r, index) => (
<Card key={r.id} {...r} onReveal={onReveal}/>
));
return (
<div className="Board">
{AllCards}
</div>
);

}
}

const CardState = {
hidden: 0,
visible: 1,
paired: 2
}

class App extends Component {
constructor(props){
super(props);
this.state = {
cards: [
{id: 0, cardState: CardState.hidden, colour: "red"},
{id: 1, cardState: CardState.hidden, colour: "red"},
{id: 2, cardState: CardState.hidden, colour: "blue"},
{id: 3, cardState: CardState.hidden, colour: "blue"},
]
};
this.onReveal = this.onReveal.bind(this);
}

onReveal(id) {
const revealedArray = this.state.cards.map((val, ind) =>
(val.id === id ?
(val = {id: id, cardState: CardState.visible, colour: val.colour}) : (val = val)
)
);
this.setState({revealedArray}, function() {
console.log(this.state.cards);
});
}


render() {
return (
<div className="App">
<div className="header">
<h1>
Memory Game
</h1>
<a><h3>
New Game
</h3></a>
</div>
<div className="body">
<CardHolder cards={this.state.cards} onReveal={this.onReveal}/>
</div>
</div>
);
}
}

export default App;

非常感谢您的帮助。

最佳答案

这些行:

this.setState({revealedArray}, function() {
console.log(this.state.cards);
});

您正在设置名为 revealedArrays 的状态变量,您想要的是

this.setState({cards: revealedArray}, function() {
console.log(this.state.cards);
});

关于javascript - 为什么我不能使用 setState 将对象传递给状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49073695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com