Javascript 在React中,如何更新映射元素数组中元素的状态?

Javascript 在React中,如何更新映射元素数组中元素的状态?,javascript,reactjs,react-props,Javascript,Reactjs,React Props,我在下面或沙箱中有两个数据对象和3个层次结构组件。数据包含一个问题列表,每个问题的下方都有一个允许多个回答的输入框。但是,我不知道如何在键入对特定问题的答复后正确更新正确问题的状态 index.js import React from 'react'; import { render } from 'react-dom'; import QA from './qa'; //parent of qa.js const questions = [ {id : 1, question: "w

我在下面或沙箱中有两个数据对象和3个层次结构组件。数据包含一个问题列表,每个问题的下方都有一个允许多个回答的输入框。但是,我不知道如何在键入对特定问题的答复后正确更新正确问题的状态

index.js

import React from 'react';
import { render } from 'react-dom';
import QA from './qa';
//parent of qa.js

const questions = [
  {id : 1,
  question: "where is the origin of chihuahua?"},
  {id : 2,
  question: "when does the great migration happen in Africa?"}
]

const answers = [
  {
    id : 1,
    id_question : 1,
    answer: "Mexico"
    },
  {
    id : 2,
    id_question : 1,
   answer: "Argentina"
  },
  {
    id : 3,
    id_question : 2,
    answer: "Apr"
    },
  {
    id : 4,
    id_question : 2,
    answer: "May"}
]

export default class App extends React.Component {
  state = {
    q : questions, 
    a : answers
    }

  handleSubmit = (val, index) => {
    alert('index',index)
    this.setState({
      ...this.state,
      a: [...this.state.a, {id_question: index, answer: val}]
    });
  }

  render() {
    console.log(this.state)
    return (
      questions.map((q, index) =>
        <QA 
          key={index} 
          question={q.question}
          onSubmit={this.handleSubmit}
          />
      )  
    )
  }
}


render(<App />, document.getElementById('root'));
从“React”导入React;
从'react dom'导入{render};
从“./QA”导入QA;
//qa.js的父级
常量问题=[
{id:1,
问题:“吉娃娃的起源在哪里?”},
{id:2,
问题:“大迁移何时在非洲发生?”
]
常数答案=[
{
id:1,
问题:1,,
答复:“墨西哥”
},
{
id:2,
问题:1,,
答复:“阿根廷”
},
{
id:3,
问题2,,
答:"四月"
},
{
id:4,
问题2,,
回答:“五月”}
]
导出默认类App扩展React.Component{
状态={
问:问题,
答:答案
}
handleSubmit=(val,index)=>{
警报('索引',索引)
这是我的国家({
…这个州,
a:[…this.state.a,{id_问题:索引,答案:val}]
});
}
render(){
console.log(this.state)
返回(
问题。地图((q,索引)=>
)  
)
}
}
render(,document.getElementById('root'));
qa.js

从“React”导入React;
从“/Answer”导入应答;
导入“/style.css”
//answer.js的父级
导出默认类QA扩展React.Component{
建造师(道具){
超级(道具)
此.state={
案文:“”
}
}
render(){
const{question}=this.props
const{text}=this.state
返回(
问题:{问题}
)
}
}
和answer.js

import React from 'react';

const styles = {
  backgroundColor: 'lightgray',
};

export default class Answer extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      text: ""
    }
  }
  render() {
    const { text } = this.state
    return (
      <div style={styles}>
        <h4>Answers</h4>
        <input type="text"
          value={text} 
          onInput={(e) => this.setState({ text: e.target.value })} />
        <button onClick={() => this.props.onSubmit(this.state.text)}>Send to the parent</button>
      </div>
    )
  }
}
render() {
    const { text } = this.state
    return (
      <div style={styles}>
        <h4>Answers</h4>
        <input type="text"
          value={text} 
          onInput={(e) => this.setState({ text: e.target.value })} />
        <button onClick={() => this.props.onSubmit(this.state.text, this.props.questionNo)}>Send to the parent</button>
      </div>
    )
  }
import React from 'react';

const styles = {
  backgroundColor: 'lightgray',
};

export default class Answer extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      text: ""
    }
  }
  render() {
    const { text } = this.state
    const {onSubmit, qid} = this.props
    return (
      <div style={styles}>
        <h4>Answers</h4>
        <input type="text"
          value={text} 
          onInput={(e) => this.setState({ text: e.target.value })} />
        <button onClick={() => onSubmit(qid, this.state.text)}>Send to the parent</button>
      </div>
    )
  }
}
从“React”导入React;
常量样式={
背景颜色:“浅灰色”,
};
导出默认类应答扩展React.Component{
建造师(道具){
超级(道具)
此.state={
案文:“”
}
}
render(){
const{text}=this.state
返回(
答案
this.setState({text:e.target.value})}/>
this.props.onSubmit(this.state.text)}>发送到父级
)
}
}
一些新手问题:

  • 我在哪里调用索引,以便setState附加到state。回答正确的问题id并将答案id增加1
  • 我应该把嵌套答案作为问题的属性吗

  • 谢谢你的帮助

    您只需将questionNo作为道具传递给qa&ans组件,然后通过回调进行检索,如下所示:

    在index.js中

    render() {
        console.log(this.state)
        return (
          questions.map((q, index) =>
            <QA 
              questionNo={index} 
              question={q.question}
              onSubmit={this.handleSubmit}
              />
          )  
        )
      }
    
    render(){
    console.log(this.state)
    返回(
    问题。地图((q,索引)=>
    )  
    )
    }
    
    在qa.js中

    render() {
        const { question, questionNo } = this.props
        const { text } = this.state
        return (
          <div class='qa-block'>
            <div>Question: {question}</div>
            <Answer questionNo={questionNo} onSubmit={this.props.onSubmit}/>
          </div>
        )
      }
    
    render(){
    const{question,questionNo}=this.props
    const{text}=this.state
    返回(
    问题:{问题}
    )
    }
    
    in answer.js

    import React from 'react';
    
    const styles = {
      backgroundColor: 'lightgray',
    };
    
    export default class Answer extends React.Component {
      constructor(props) {
        super(props)
        this.state = {
          text: ""
        }
      }
      render() {
        const { text } = this.state
        return (
          <div style={styles}>
            <h4>Answers</h4>
            <input type="text"
              value={text} 
              onInput={(e) => this.setState({ text: e.target.value })} />
            <button onClick={() => this.props.onSubmit(this.state.text)}>Send to the parent</button>
          </div>
        )
      }
    }
    
    render() {
        const { text } = this.state
        return (
          <div style={styles}>
            <h4>Answers</h4>
            <input type="text"
              value={text} 
              onInput={(e) => this.setState({ text: e.target.value })} />
            <button onClick={() => this.props.onSubmit(this.state.text, this.props.questionNo)}>Send to the parent</button>
          </div>
        )
      }
    
    import React from 'react';
    
    const styles = {
      backgroundColor: 'lightgray',
    };
    
    export default class Answer extends React.Component {
      constructor(props) {
        super(props)
        this.state = {
          text: ""
        }
      }
      render() {
        const { text } = this.state
        const {onSubmit, qid} = this.props
        return (
          <div style={styles}>
            <h4>Answers</h4>
            <input type="text"
              value={text} 
              onInput={(e) => this.setState({ text: e.target.value })} />
            <button onClick={() => onSubmit(qid, this.state.text)}>Send to the parent</button>
          </div>
        )
      }
    }
    
    render(){
    const{text}=this.state
    返回(
    答案
    this.setState({text:e.target.value})}/>
    this.props.onSubmit(this.state.text,this.props.questionNo)}>发送到父级
    )
    }
    

    在此之后,您将在index.js中获得单击项的索引,您只需将问号作为道具传递给qa&ans组件,然后通过回调进行检索,如下所示:

    render() {
        console.log(this.state)
        return (
          questions.map((q, index) =>
            <QA 
              questionNo={index} 
              question={q.question}
              onSubmit={this.handleSubmit}
              />
          )  
        )
      }
    
    在index.js中

    render() {
        console.log(this.state)
        return (
          questions.map((q, index) =>
            <QA 
              questionNo={index} 
              question={q.question}
              onSubmit={this.handleSubmit}
              />
          )  
        )
      }
    
    render(){
    console.log(this.state)
    返回(
    问题。地图((q,索引)=>
    )  
    )
    }
    
    在qa.js中

    render() {
        const { question, questionNo } = this.props
        const { text } = this.state
        return (
          <div class='qa-block'>
            <div>Question: {question}</div>
            <Answer questionNo={questionNo} onSubmit={this.props.onSubmit}/>
          </div>
        )
      }
    
    render(){
    const{question,questionNo}=this.props
    const{text}=this.state
    返回(
    问题:{问题}
    )
    }
    
    in answer.js

    import React from 'react';
    
    const styles = {
      backgroundColor: 'lightgray',
    };
    
    export default class Answer extends React.Component {
      constructor(props) {
        super(props)
        this.state = {
          text: ""
        }
      }
      render() {
        const { text } = this.state
        return (
          <div style={styles}>
            <h4>Answers</h4>
            <input type="text"
              value={text} 
              onInput={(e) => this.setState({ text: e.target.value })} />
            <button onClick={() => this.props.onSubmit(this.state.text)}>Send to the parent</button>
          </div>
        )
      }
    }
    
    render() {
        const { text } = this.state
        return (
          <div style={styles}>
            <h4>Answers</h4>
            <input type="text"
              value={text} 
              onInput={(e) => this.setState({ text: e.target.value })} />
            <button onClick={() => this.props.onSubmit(this.state.text, this.props.questionNo)}>Send to the parent</button>
          </div>
        )
      }
    
    import React from 'react';
    
    const styles = {
      backgroundColor: 'lightgray',
    };
    
    export default class Answer extends React.Component {
      constructor(props) {
        super(props)
        this.state = {
          text: ""
        }
      }
      render() {
        const { text } = this.state
        const {onSubmit, qid} = this.props
        return (
          <div style={styles}>
            <h4>Answers</h4>
            <input type="text"
              value={text} 
              onInput={(e) => this.setState({ text: e.target.value })} />
            <button onClick={() => onSubmit(qid, this.state.text)}>Send to the parent</button>
          </div>
        )
      }
    }
    
    render(){
    const{text}=this.state
    返回(
    答案
    this.setState({text:e.target.value})}/>
    this.props.onSubmit(this.state.text,this.props.questionNo)}>发送到父级
    )
    }
    

    在此之后,您将在index.js中获得单击项的索引,因此要确定问题,您需要将id_问题传递给submit按钮,因此如果您有参数,则可以在回调中获得它

    render() {
        console.log(this.state)
        return (
          questions.map((q, index) =>
            <QA 
              questionNo={index} 
              question={q.question}
              onSubmit={this.handleSubmit}
              />
          )  
        )
      }
    
    一旦你得到了答案,你就可以在对象的答案数组中进行查找并更新用户类型的答案

      handleSubmit = (val, text) => {
        const typedAnswer = {...this.state.a.find(ans => ans.id_question === val), userTypedAnswer: text};
        this.setState({
          ...this.state,
          a: [...this.state.a, typedAnswer]
        });
      }
    
    代码

    index.js

    import React from 'react';
    import { render } from 'react-dom';
    import QA from './qa';
    //parent of qa.js
    
    const questions = [
      {id: 1,
      question: "where is the origin of chihuahua?"},
      {id: 2,
      question: "when does the great migration happen in africa?"}
    ]
    
    const answers = [
      {id_question: 1,
      answer: "Mexico"},
      {id_question: 1,
      answer: "Argentina"},
      {id_question: 2,
      answer: "Apr"},
      {id_question: 2,
      answer: "May"}
    ]
    
    export default class App extends React.Component {
      state = {
        q : questions, 
        a : answers
        }
    
      handleSubmit = (val, text) => {
        const typedAnswer = {...this.state.a.find(ans => ans.id_question === val), userTypedAnswer: text};
        this.setState({
          ...this.state,
          a: [...this.state.a, typedAnswer]
        });
      }
    
      render() {
        return (
          <>{
             questions.map((q, index) =>
            <QA 
              key={index} 
              question={q}
              onSubmit={this.handleSubmit}
              />
          )  
    
          }
           <p>User Typed Answers and questions after submit</p>
           {
             this.state.a.map(ans => (
               ans.userTypedAnswer && <div>
                <span>{ans.id_question}</span>: <span>{ans.userTypedAnswer}</span>
               </div>
             ))
           }
          </>
        )
      }
    }
    
    
    render(<App />, document.getElementById('root'));
    
    从“React”导入React;
    从'react dom'导入{render};
    从“./QA”导入QA;
    //qa.js的父级
    常量问题=[
    {id:1,
    问题:“吉娃娃的起源在哪里?”},
    {id:2,
    问题:“大迁移何时在非洲发生?”
    ]
    常数答案=[
    {问题:1,
    答:"墨西哥",,
    {问题:1,
    答复:“阿根廷”},
    {问题:2,
    答:"Apr",,
    {问题:2,
    回答:“五月”}
    ]
    导出默认类App扩展React.Component{
    状态={
    问:问题,
    答:答案
    }
    handleSubmit=(val,text)=>{
    consttypedanswer={…this.state.a.find(ans=>ans.id_question==val),userTypedAnswer:text};
    这是我的国家({
    …这个州,
    a:[…这个.州.a,输入丹麦语]
    });
    }
    render(){
    返回(
    {
    问题。地图((q,索引)=>
    )  
    }
    提交后用户键入答案和问题

    { this.state.a.map(ans=>( ans.userTypedAnswer& {ans.id_question}:{ans.userTypedAnswer} )) } ) } }
    render(

    因此,要识别问题,您需要将id\u问题传递给submit按钮,这样,如果您有参数,那么在回调中您将能够获得它

    一旦你得到了答案,你就可以在对象的答案数组中进行查找并更新用户类型的答案

      handleSubmit = (val, text) => {
        const typedAnswer = {...this.state.a.find(ans => ans.id_question === val), userTypedAnswer: text};
        this.setState({
          ...this.state,
          a: [...this.state.a, typedAnswer]
        });
      }
    
    代码

    index.js

    import React from 'react';
    import { render } from 'react-dom';
    import QA from './qa';
    //parent of qa.js
    
    const questions = [
      {id: 1,
      question: "where is the origin of chihuahua?"},
      {id: 2,
      question: "when does the great migration happen in africa?"}
    ]
    
    const answers = [
      {id_question: 1,
      answer: "Mexico"},
      {id_question: 1,
      answer: "Argentina"},
      {id_question: 2,
      answer: "Apr"},
      {id_question: 2,
      answer: "May"}
    ]
    
    export default class App extends React.Component {
      state = {
        q : questions, 
        a : answers
        }
    
      handleSubmit = (val, text) => {
        const typedAnswer = {...this.state.a.find(ans => ans.id_question === val), userTypedAnswer: text};
        this.setState({
          ...this.state,
          a: [...this.state.a, typedAnswer]
        });
      }
    
      render() {
        return (
          <>{
             questions.map((q, index) =>
            <QA 
              key={index} 
              question={q}
              onSubmit={this.handleSubmit}
              />
          )  
    
          }
           <p>User Typed Answers and questions after submit</p>
           {
             this.state.a.map(ans => (
               ans.userTypedAnswer && <div>
                <span>{ans.id_question}</span>: <span>{ans.userTypedAnswer}</span>
               </div>
             ))
           }
          </>
        )
      }
    }
    
    
    render(<App />, document.getElementById('root'));
    
    从“React”导入React;
    从'react dom'导入{render};
    从“”导入QA。