невозможно отобразить данные при выборе конкретной кнопки - PullRequest
0 голосов
/ 22 сентября 2019

выборка данных из API и их отображение, но я хочу отобразить информацию о соответствующих выбранных данных с помощью переключателя, но не могу отобразить данные при выборе переключателя
, если условие не работает в handleData(), поэтому любой из них скажетгде я делаю не так

import React, {component, useStates} from 'react';

import axios from 'axios';

export default class Posts extends React.Component {
    constructor(){
        super();
        this.handleData = this.handleData.bind(this);
  this. state = {
    details: [],
    selected: [],
    hndleres:[]
  }
}
   // pagination



  componentDidMount() {
   this.renderData();
   this.displyhandleData();
  }

  renderData(){
    axios.get(`https://jsonplaceholder.typicode.com/posts`)
    .then(res => {
      const details = res.data;
      this.setState({ details });
    })
  }

   renderList(){
      return(this.state.details).map((data, index) =>{
            const uID = data.userId
            const ID = data.id
            const Body =data.body
            const Title = data.title
            return(
                    <tr>
                        <td><input type="radio" name="details" value={ID} onChange={this.handleData}></input></td>
                        <td>{ID}</td>
                        <td>{uID}</td>
                        <td>{Title}</td>
                        <td>{Body}</td>

                    </tr>

            )
   } )

  }
  handleData = (e) => {

    this.state.value = e.target.value;
    //debugger;
    console.log(e.target.value)
    debugger;
    if(e.target.value != '1')
    {
        debugger;
        let url = 'https://jsonplaceholder.typicode.com/posts'
        const data = { "ID": e.target.value }
        const res= axios.get(url, data)
        .then(res =>{
            this.setState = ({  hndleres : res.data})

        });
    }
    else{
        this.displyhandleData();
    }

}

displyhandleData(){
    return(this.state.hndleres).map((datas,index) =>{
        const uID = datas.userId
        const ID = datas.id
        const Body =datas.body
        const Title = datas.title
        return(
                <tr>
                     <td><input type="radio" name="details" value={ID} onChange={this.handleData}></input></td>
                    <td>{ID}</td>
                    <td>{uID}</td>
                    <td>{Title}</td>
                    <td>{Body}</td>

                </tr>

        )
      })
}
  render() {
    return (
        <div>
      <table className="table">
        { this.renderList()}
      </table>
      <table className="table">
        { this.displyhandleData()}
      </table>

      </div>
    )
  }
}

поэтому кто-нибудь скажет мне, где я делаю не так

рендерит данные из API, но не отображает данные выбранного радиокнопки:

1 Ответ

1 голос
/ 22 сентября 2019

В вашем коде есть несколько проблем, таких как прямое изменение состояния, передача параметров obj в axios и переопределение функции this.setState вместо ее вызова.Я исправил несколько.Посмотрите и дайте мне знать, если это поможет

import React from "react";

import axios from "axios";

export default class Posts extends React.Component {
  constructor() {
    super();
    this.handleData = this.handleData.bind(this);
    this.state = {
      details: [],
      selected: [],
      hndleres: []
    };
  }
  // pagination

  componentDidMount() {
    this.renderData();
    this.displyhandleData();
  }

  renderData() {
    axios.get(`https://jsonplaceholder.typicode.com/posts`).then(res => {
      const details = res.data;
      this.setState({ details });
    });
  }

  renderList() {
    return this.state.details.map((data, index) => {
      const uID = data.userId;
      const ID = data.id;
      const Body = data.body;
      const Title = data.title;
      return (
        <tr>
          <td>
            <input
              type="radio"
              name="details"
              value={ID}
              onChange={this.handleData}
            ></input>
          </td>
          <td>{ID}</td>
          <td>{uID}</td>
          <td>{Title}</td>
          <td>{Body}</td>
        </tr>
      );
    });
  }
  handleData = e => {
    //debugger;
    console.log(e.target.value);
    debugger;
    if (e.target.value != "1") {
      debugger;
      let url = "https://jsonplaceholder.typicode.com/posts";
      const data = { userId: e.target.value };
      axios.get(url, { params: data }).then(res => {
        this.setState({ hndleres: res.data });
      });
    } else {
      this.displyhandleData();
    }
  };

  displyhandleData() {
    return this.state.hndleres.map((datas, index) => {
      const uID = datas.userId;
      const ID = datas.id;
      const Body = datas.body;
      const Title = datas.title;
      return (
        <tr>
          <td>
            <input
              type="radio"
              name="details"
              value={ID}
              onChange={this.handleData}
            ></input>
          </td>
          <td>{ID}</td>
          <td>{uID}</td>
          <td>{Title}</td>
          <td>{Body}</td>
        </tr>
      );
    });
  }
  render() {
    return (
      <div>
        <table className="table">{this.renderList()}</table>
        <table className="table">{this.displyhandleData()}</table>
      </div>
    );
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...