微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

react js class poll 转换成react hooks poll

如何解决react js class poll 转换成react hooks poll

这是我用于反应组件“类”基础轮询的代码,但我想将此表单转换为反应钩子,因此需要帮助...!我不明白我该怎么做...!请帮助请帮助帮助 请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助请帮助

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 钩子。

转换步骤:

  1. 转换状态以使用 useState React 钩子。
  2. this.state.pollAnswers 的引用替换为 pollAnswers
  3. 将对 this.setState 的引用替换为 setPollAnswers
  4. 使用适当的功能状态更新不要改变现有状态。
  5. 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;

Edit react-js-class-poll-convert-into-react-hooks-poll

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。