reactjs - 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?
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```
解决方案
我看不到的东西,所以我要假设;
你的上下文应该包含一个状态和动作。
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>
);
推荐阅读
- android-studio - 找不到 appcompat.jar
- android - 如何使用 Python 从 Android 手机关闭 Windows 计算机
- python - Python Asyncio:如何等待某事?
- javascript - 如何只允许单个引导弹出元素
- vue.js - Vue使用来自JSON的数据显示模态点击
- python - 如何使 for 循环保持返回值?
- angular - Nativescript Run (iOS) 几乎不再工作了
- amazon-web-services - 生成的 Lambda 角色定义中的受信任实体是什么?
- c++ - 防止客户端套接字程序崩溃 cpp google protobuf
- reactjs - setState 不适用于导入类组件