首页 > 解决方案 > How am I getting this JS error from

element?

问题描述

I have a <Form /> component in my React app that renders 4 input fields. Only the 1st is editable (which has an onChange handler). If I edit it, it should update the corresponding property of my question objects inside my list. But when I am typing, it is giving me

"TypeError: Cannot read property 'map' of undefined" at line 16.

This line has <button>Discard</button>. Why is it giving me this error in the line which includes only HTML, not JS?

Screenshot: enter image description here

import {QuizContext} from '../QuizContext';
import {QuizContextProvider} from '../QuizContext';


const Form = () => {

    const {yourQuestions, setYourQuestion} = useContext(QuizContext)

    return (
        <div style={{textAlign: 'center'}}>
            {console.log(yourQuestions)}
            
            <div>
            <button>Add the next question</button>
            <button>Discard</button>
            </div>

            {yourQuestions.map((question, index, array)=>{
                return (
                    <div key={question.id}>
                    <input readOnly style={{display: 'block'}} value={question.question}/>
                    <input value={question.answer_a} 
                    onChange={(e)=>{
                        setYourQuestion((Questions) => { //currentQuestions is 'yourQuestions' array
                            Questions.map((currentQuestion, currentIndex, currentArray)=>{
                                console.log(yourQuestions)
                                return (
                                 (currentQuestion.id === question.id) ? {
                                  ...currentQuestion,
                                  answer_a : e.target.value
                                } 
                                : currentQuestion
                                )
                            })
                        }
                        )
                    }} />
                    <input value={question.answer_b} readOnly />
                    <input value={question.answer_c} readOnly />
                    <input value={question.answer_d} readOnly />
                    <div>
                    <input style={{width: 'auto'}} placeholder='Type the correct answer again...' value={question.correct_answer} readOnly />
                    </div>
                    </div>
                )
            })}
            <div>{JSON.stringify(yourQuestions, null, 2)}</div>
            {console.log(yourQuestions)}
        </div>            
    )
}

export default Form```

标签: reactjs

解决方案


我看不到的东西,所以我要假设;

你的上下文应该包含一个状态和动作。

const { state, actions } = useContext(WhateverContexts);

我还将检查您可以在map方法中传递的参数。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

地图使用示例:

const todoItems = todos.map((todo, index) =>
  // Only do this if items have no stable IDs
  <li key={index}>
    {todo.text}
  </li>
);

推荐阅读