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

为什么在 React Button 组件中第二次单击后 Action up 会中断?

如何解决为什么在 React Button 组件中第二次单击后 Action up 会中断?

我目前正在我的 React 应用中实现关注按钮。我提出了一个操作,以便 FollowButton(父组件)能够控制 Unfollow 组件的呈现,具体取决于以下是否存在或 Follow 组件(如果不存在)。

在我第一次点击时有效,但在我从 API 获得“未找到以下内容”之后。 第二次点击 Unfollow 后,控制台显示 URL:“http://localhost:3000/api/v1/followings/undefined”。

我尝试在组件周围使用 debuggerconsole.log 来遵循代码以遵循每个函数中的值。

这是我的代码

关注按钮

import React,{Component} from 'react';
import Follow from '../create';
import Unfollow from '../delete';

class FollowButton extends Component {
  constructor(props) {
    super(props);
    this.updateFollowing = this.updateFollowing.bind(this);
    this.state = {
      following: null,}
  }

  async getFollowingIfExist(authorId) {

    const url = `http://localhost:3000/api/v1/get_following?author_id=${authorId}`;

    const storagetoken = localStorage.getItem('auth_token');

    const bearer = 'Bearer ' + storagetoken;

    const settings = {
      method: 'GET',headers: {
        'Authorization': bearer,'Content-Type': 'application/json'
      }
    };

    try {
      const response = await fetch(url,settings)

      const result = await response.json();

      if(result && result.following) {

        const following = result.following

        this.setState({
          following: following,})
      }
    } catch(e) {
      if (e instanceof TypeError) {
        console.error("API response error");
        console.error(e);
        alert("Oops something went wrong. Please try again soon.");
      }
    }
  };

  componentDidMount() {
    this.getFollowingIfExist(this.props.authorId);
  }

  updateFollowing(following) {
    this.setState({
      following: following,})
  }

  render() {

    const {following} = this.state;

    if (!following) {

      return(
        <div>
          < Follow authorId={this.props.authorId}
            updateFollowing={this.updateFollowing} />
        </div>
      )

     } else {

       return (
         <div>
           < Unfollow followingId={following.id}
             updateFollowing={this.updateFollowing} />
         </div>
       )
     }
  }
}

export default FollowButton

关注创建组件

import React,{Component} from 'react';
import  'bootstrap/dist/css/bootstrap.min.css';
import {Container,Button,Row,Col} from 'react-bootstrap';

class Follow extends Component {
  constructor(props) {
    super(props);

    this.state = {
      error: false,followCreated: false,}

    this.createFollow = this.createFollow.bind(this);
  }

  async createFollow(e) {

    e.preventDefault();

    const url = 'http://localhost:3000/api/v1/followings';

    const storagetoken = localStorage.getItem('auth_token')

    const bearer = 'Bearer ' + storagetoken;

    const settings = {
      method: 'POST','Content-Type': 'application/json'
      },body: JSON.stringify({author_id: this.props.authorId})
    };

    try {
      const response = await fetch(url,settings)

      const result = await response.json();

      if (result.error) {
        this.setState({
          error: true,})
        alert(result.message);
      } else {
        this.setState({
          followCreated: true,})
        this.props.updateFollowing(true);
      }

    } catch(e) {
      if (e instanceof TypeError) {
        console.error("API response error")
        console.error(e);
        alert("Oops something went wrong. Please try again soon.");
      }
    }

  };

  render() {

    return(
      <div>
        <Container>
          <Row>
            <Col md={{ span: 6,offset: 3 }}>
              <Button variant="outline-success" onClick={(e) => this.createFollow(e)}>Follow author</Button>
            </Col>
          </Row>
        </Container>
       </div>
    )
  };

};

export default Follow

取消关注组件

import React,Col} from 'react-bootstrap';

class Unfollow extends Component {
  constructor(props) {
    super(props);

    this.state = {
      error: false,followDeleted: false,}
  }

  async unFollow(e,followingId) {

    e.preventDefault();

    const url = `http://localhost:3000/api/v1/followings/${followingId}`;

    const storagetoken = localStorage.getItem('auth_token')

    const bearer = 'Bearer ' + storagetoken;

    const settings = {
      method: 'DELETE',};

    try {
      debugger;
      const response = await fetch(url,settings)

      const result = await response.json();
      debugger;

      if (result.error) {
        this.setState({
          error: true,})
        alert(result.message);
      } else {
        this.setState({
          followDeleted: true,})
        this.props.updateFollowing(false);
      }

    } catch(e) {
      if (e instanceof TypeError) {
        console.error("API response error")
        console.error(e);
        alert("Oops something went wrong. Please try again soon.");
      }
    }

  };

  render() {

    return(
      <div>
        <Container>
          <Row>
            <Col md={{ span: 6,offset: 3 }}>
              <Button variant="outline-secondary" onClick={(e,followingId) => this.unFollow(e,this.props.followingId)}>Unfollow</Button>
            </Col>
          </Row>
        </Container>
       </div>
    )
  };

};

export default Unfollow

以下控制器

class Api::V1::FollowingsController < Api::ApplicationController

  def create
    following = Following.new
    following.follower_id = @current_api_user.id
    following.author_id = params[:author_id]

    following_exist = Following.find_by(follower_id: @current_api_user.id,author_id: params[:author_id])
    if following_exist
      render json: { message: "following exist already",error: true },status: 400
    elsif following.follower_id == following.author_id
      render json: { message: "cant follow yourself",status: 400
    elsif following.save
      render json: { following: following,message: "successful following" },status: 201
    else
      render json: { message: "Oops we Could not follow this user for you. Please try again soon",errors: following.errors.full_messages,status: 400
    end
  end

  # check if there's an existing following already wih the current user and
  # the author_id
  def get_following
    # check if theres an author_id
    author_id = params[:author_id]
    # if the following exist return the following,else will be null
    if !author_id
      render json: { error: true,message: "author_id not found" },status: 400
    else
      following = Following.find_by(follower_id: @current_api_user.id,author_id: author_id)
      render json: { following: following },status: 200
    end
  end

  def destroy

      following = Following.find_by(id: params[:id])

      if !following
        render json: { error: true,message: "following not found" },status: 400
      else
        following.destroy
        render json: { message: "successful unfollow" },status: 202
      end
  end

end

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

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?