【问题标题】:Can not pass array with objects as prop in react无法在反应中将带有对象的数组作为道具传递
【发布时间】:2020-06-25 07:15:42
【问题描述】:

我正在从 axio 获取响应获取请求更新挂载状态并尝试将响应传递给其他组件。

来自 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;

我遇到的问题是状态中的 questions 无法将传递作为道具。我不断得到 questions 变量的空数组。我什么都试过了。任何帮助将不胜感激!

【问题讨论】:

  • 你能看到你的ChangeQuestions类里面的问题吗?
  • ChangeQuestions 组件中的{console.log(operator_preferences)} 得到了什么?
  • QuestionTable 应该实现componentDidUpdate 生命周期函数,以便在questions 属性更改时(即当数据填充到ChangeQuestions 时)获取。
  • 是的,我可以看到 [{}] 格式的响应 = 问题,然后才能作为道具传递
  • console.log(props.questions)放到QuestionTable的render函数里面你可能会看到数据

标签: javascript reactjs api react-native axios


【解决方案1】:

您好,您可以在 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});
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 2021-03-11
    • 1970-01-01
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多