Я застрял на проблеме передачи моего состояния функциям вне класса. Я новичок в кодировании в целом, но я почти уверен, что мне нужно использовать либо хуки, либо контекст, либо Redux, чтобы завершить это. Сначала позвольте мне опубликовать свой код.
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: 10,
ran: "",
id: "",
temp: Math.floor(Math.random() * 3 + 1),
draw: {
score: 0
},
user: {
score: 0,
choice: ""
},
pc: {
score: 0,
choice: ""
},
roundLimit: 10,
roundWinner: ""
};
this.setWinner = this.setWinner.bind(this);
this.setWeapon = this.setWeapon.bind(this);
this.battle = this.battle.bind(this);
this.attack = this.attack.bind(this);
}
setWeapon = (pcId, userId) => {
const [ pcWeaponName, userWeaponName] = [pcId, userId].map(weaponId => weapons.find(w => w.weaponId === weaponId).name);
console.log(this.state.pc.choice, pcWeaponName)
this.setState({
user: { score: this.state.user.score, choice: userWeaponName },
pc: { score: this.state.pc.score, choice: pcWeaponName }
});
};
setWinner = (winner = "draw") => {
const { score, choice } = this.state[winner];
const newScore = score + 1;
this.setState({
roundWinner: winner,
[winner]: { score: newScore, choice }
});
};
battle = userWeaponId => {
//Get PC Choice
const generatePcWeapon = () =>
[...weapons][Math.floor(Math.random() * weapons.length)];
const pcWeapon = generatePcWeapon();
const { weaponId: pcWeaponId, weaknesses = [] } = pcWeapon;
// Get User Choice
// Compare IDs
if (pcWeaponId === userWeaponId) {
// Update roundWinner to Draw
this.setWinner();
// Return
return;
}
// Search for user choice in PC Weaknesses
this.setWeapon(pcWeaponId, userWeaponId);
const winner = weaknesses.includes(userWeaponId) ? "user" : "pc";
this.setWinner(winner);
};
attack = id => {
this.battle(id); // your alert function
};
render(props) {
const { user, pc, roundWinner } = this.state;
return (
<>
<div className="container">
<Container fluid>
<Row>
<Col>
<h5>Rock, Paper, Scissors</h5>
</Col>
</Row>
<Row>
<Col>
<h6> Select Your Weapon </h6>
</Col>
</Row>
{weapons.map(({ name, weaponId }) => {
return (
<Row key={weaponId}>
<Col>
<WeaponButton
attackAction={this.attack}
id={weaponId}
name={name}
/>
</Col>
</Row>
);
})}{" "}
</Container>
</div>
<ReactInfo
id={user.choice}
ran={pc.choice}
roundWinner={roundWinner}
userPoint={user.score}
pcPoint={pc.score}
/>
</>
);
}
}
export default Counter;
Это мой класс счетчика. Это функциональные возможности предупреждений, которые я пытаюсь использовать для состояний из класса:
const ScoreRecord = () => {
const { userPoint, pcPoint } = this.props;
return (
<p>
The score is You:{userPoint} to PC:{pcPoint}
</p>
);
};
export function doAlert ({ props }) {
const { roundWinner, userPoint, pcPoint } = props;
const isSuccess = roundWinner === "User";
const message = isSuccess ? "You won dude." : "Youre fucking lame";
const title = isSuccess ? "Winner" : "Boo";
const DoAlert = (<AlertComponent isSuccess={isSuccess} message={message} title={title}>
<ScoreRecord userPoint={userPoint} pcPoint={pcPoint} />
</AlertComponent>
);
export function AlertMessageForm ({ children, isSuccess, message, title, scores }) {
return (
<Alert variant={isSuccess ? "success" : "info"} dismissible>
<Alert.Heading>{title}!</Alert.Heading>
<p>{message}</p>
<hr />
{children}
</Alert>
);
};
А вот код и ящик ссылка
Любые указания будут оценены.