繁体   English   中英

无法在反应中将带有对象的数组作为道具传递

[英]Can not pass array with objects as prop in react

我收到来自 axio get request 的响应,更新 state 并尝试将响应传递给其他组件。

来自ChangeQuestions.js 的代码:

import React from 'react';
import UserService from "../../services/user.service";
import QuestionTable from './QuestionTable.js'

class ChangeQuestions extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      operator_personal: [],
      operator_preferences: [],
      company_questions: [],
    }
  }

  componentDidMount(){
    UserService.getOperatorPersonalQuestions()
      .then(({ data }) => {
        this.setState({ operator_personal:  data });
      })
      .catch((err) => {})

    UserService.getOperatorPreferencesQuestions()
      .then(({ data }) => {
        this.setState({ operator_preferences:  data });
      })
      .catch((err) => {})

    UserService.getCompanyQuestions()
      .then(({ data }) => {
        this.setState({ company_questions: data });
      })
      .catch((err) => {})
  }
   
  render(){
    const { operator_personal, operator_preferences, company_questions } = this.state;
    return (
      <div>
        {console.log(operator_preferences)}
        <QuestionTable questions={operator_personal}/>
        <QuestionTable questions={operator_preferences}/>
        <QuestionTable questions={company_questions}/>  
        {/* <QuestionTable questions={this.state.connections}/>*/}
      </div>
    );
  }
}

这是来自QuestionTable组件的代码:

import React from 'react';
import Table from 'react-bootstrap/Table';

class QuestionTable extends React.Component{
  constructor(props){
    super(props);
    console.log(props.questions);
    this.state = {
       questions: this.props.questions,
       edit: []
    };
    this.addNewTab = this.addNewTab.bind(this);
  }

  componentDidMount(){
    this.setState(prev => ({
        edit: prev.questions.map(() => [...prev.edit, false]),
        questions: [...this.props.questions]
    }))
  }

  handleEdit = index => {
    this.setState(state => {
      const list = state.edit.map((item, j) => {
        if (j === index) {
          return !item;
        } else {
          return item;
        }
      });
      return {
        edit: list
      };
    });
  }

  handleTitleChange = index => {
    this.setState(state => {
      let temp = {
        "id": '',
        "answers": [ ],
        "typeprofile": "",
        "questiontext": ""
      };
      const list = state.questions.map((it, j) => {
        if (index == j) {
          temp.id = it.id;
          temp.answers = it.answerss;
          temp.typeprofile = it.typeprofile;
          temp.questiontext = document.getElementById(`title${index}`).value;
          return temp;
        }
        return it;
      })
      return {
        questions: list,
      };
    });
  }
  
  handleAnswersChange = index => {
    this.setState(state => {
      let temp = {
        "id": '',
        "answers": [ ],
        "typeprofile": "",
        "questiontext": "",
        "connection": 0
      };
      const string = document.getElementById(`answers${index}`).value;
      const list = state.questions.map((it, j) => {
        if (index == j) {
          temp.id = it.id;
          if (string.indexOf(',') > -1) { 
            temp.answers = string.split(',');
          }
          else temp.answers = [string];
          temp.typeprofile = it.typeprofile;
          temp.questiontext = it.questiontext;
          return temp;
        }
        return it;        
      })
      return {
        questions: list,
      };
    });
  }

  addNewTab(event) {
    event.preventDefault();
    let temp = {
      "id": '',
      "answers": [ ],
      "typeprofile": "",
      "questiontext": "",
      "connection": 0
    };

    this.setState({
      questions: [...this.state.questions, temp],
      edit: [...this.state.edit, true]
    })
  }

  handleDelete = (index) => {
    let array = [...this.state.questions]; // make a separate copy of the array
    let editNew = [...this.state.edit]; 
    if (index !== -1) {
      array.splice(index, 1);
      editNew.splice(index,1)
      this.setState({questions: array, edit: editNew});
    }
  }

  render(){
    const questions = this.state.questions;
    const newSelector = (ans) => {
      const {questions} = this.state;
      return(
        <select>
          {questions.map((it,j) => {
            const temp = ans;
            console.log(temp.length);
            for(let i = 0 ; i<temp.length;i++)
              return(
                <option key={j}>
                  {temp[j]}
                </option>
              );
            })}
         </select>
      );
    }
    return (
        <div>
           <Table striped bordered hover>
             <thead className='bgvi'>
               <tr>
                 <th>Pitanja</th>
                 <th>Odgovori</th>
                 <th>Edituj</th>
               </tr>
             </thead>                
             <tbody>
               {questions.length>=1&&(
               questions.map((item, index) => {
                 return(
                   <>
                     <tr className='even'>
                       <td key = {item.id}>
                         {this.state.edit[index]?
                         (
                           <textarea value={item.questiontext} id={`title${index}`} onChange={() => this.handleTitleChange(index)}  type="text"/>
                         ):
                         (                                            
                           <p>{item.questiontext}</p>
                         )}
                       </td>
                       <td key = {item.id}>
                         {(item.answers.length === 1 || item.answers.length === 0 ) && index===0?
                           (
                            this.state.edit[index]?
                            (
                              <textarea value={item.answers} id={`answers${index}`} onChange={() => this.handleAnswersChange(index)} type="text"/>
                            ):
                            (                                            
                              <p>{item.answers}</p>
                            )
                          ):(
                            this.state.edit[index]?
                              (
                                <textarea value={item.answers} id={`answers${index}`} onChange={() => this.handleAnswersChange(index)} type="text"/>
                                                
                              ):
                              (
                                newSelector(item.answers,index)
                              )
                            )}
                          </td>
                          <td key = {item.id}>                     
                            {this.state.edit[index]?
                              (
                                <button onClick={() => this.handleEdit(index)}>Sačuvaj</button>
                              ):
                              (
                                <button onClick={() => this.handleEdit(index)}>Edituj</button>
                              )}
                            <button onClick={() => this.handleDelete(index)}>Izbriši</button>

                          </td>
                          <button id="addNewTab" onClick={this.addNewTab}>Dodaj</button>
                        </tr>
                      </>
                    );
                  }
                )
              )
            }
          </tbody>
        </Table>
      </div>
    );
  }
}


export default QuestionTable;

我遇到的问题是来自 state 的问题无法通过作为道具。 我不断收到问题变量的空数组。 我什么都试过了。 任何帮助,将不胜感激!

您好,您可以在 QuestionTable 组件中添加这段代码

componentDidUpdate(prevProps,prevState) {
  // Typical usage (don't forget to compare props):
  if (this.props.questions !== prevProps.questions) {
       let newQuestions = [...this.props.questions];
    this.setState({questions:newQuestions});
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM