问题描述
这是我用于反应组件“类”基础轮询的代码,但我想将此表单转换为反应钩子,因此需要帮助...!我不明白我该怎么做...!请帮助请帮助帮助 请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助
import React,{ Component } from "react";
import Poll from "react-polls";
// Declaring poll question and answers
const pollQuestion = "Youtube is the best place to learn ?";
const pollAnswers = [
{ option: "Yes",Votes: 7 },{ option: "No",Votes: 2 },{ option: "don't kNow",Votes: 1 },];
class Fakepolls extends Component {
// Setting answers to state to reload the component with each Vote
state = {
pollAnswers: [...pollAnswers],};
// Handling user Vote
// Increments the Votes count of answer when the user Votes
handleVote = (VoteAnswer) => {
const { pollAnswers } = this.state;
const newPollAnswers = pollAnswers.map((answer) => {
if (answer.option === VoteAnswer) answer.Votes++;
return answer;
});
this.setState({
pollAnswers: newPollAnswers,});
};
render() {
const { pollAnswers } = this.state;
return (
<div>
<Poll
question={pollQuestion}
answers={pollAnswers}
onVote={this.handleVote}
/>
</div>
);
}
}
export default Fakepolls;
解决方法
对于这个答案,我假设您更喜欢询问如何将基于类的组件转换为功能组件,因为没有任何东西可以转换为自定义的 React 钩子。
转换步骤:
- 转换状态以使用
useState
React 钩子。 - 将
this.state.pollAnswers
的引用替换为pollAnswers
。 - 将对
this.setState
的引用替换为setPollAnswers
。 - 使用适当的功能状态更新不要改变现有状态。
- 将
this.handleVote
的引用替换为handleVote
并声明const
。
代码
import React,{ useState } from "react";
import Poll from "react-polls";
// Declaring poll question and answers
const pollQuestion = "Youtube is the best place to learn ?";
const answers = [ // <-- renamed to avoid collision with state variable
{ option: "Yes",votes: 7 },{ option: "No",votes: 2 },{ option: "don't know",votes: 1 }
];
const Fakepolls = () => {
// Setting answers to state to reload the component with each vote
const [pollAnswers,setPollAnswers] = useState([...answers]);
// Handling user vote
// Increments the votes count of answer when the user votes
const handleVote = (voteAnswer) => {
setPollAnswers((pollAnswers) =>
pollAnswers.map((answer) =>
answer.option === voteAnswer
? {
...answer,votes: answer.votes + 1
}
: answer
)
);
};
return (
<div>
<Poll
question={pollQuestion}
answers={pollAnswers}
onVote={handleVote}
/>
</div>
);
};
export default Fakepolls;