![](/img/trans.png)
[英]How can I access a property in an array of objects that is set in the state in react?
[英]How Can I access a property of an object array set in state
我正在为我在 scrimba 上的最终反应课程构建我的第一个反应应用程序,我正在从 API 检索数据并将部分数据设置为设置为状态的数组,但我似乎无法访问数组的属性
import React from 'react' const [request, setRequest] = React.useState([]) React.useEffect (() => { fetch('https://opentdb.com/api.php?amount=5') .then(res => res.json()) .then(data => setRequest(data.results.map(({ question, correct_answer, incorrect_answers }) => ({question, correct_answer, incorrect_answers})))) }, []) console.log(request[0]) // returns the first object array console.log(request[0]["question"]) // gives an error console.log(requst[0].question) // gives an error
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
但我似乎无法访问数组的属性
当然可以,但仅当该数组元素存在时。 数组的初始状态为空:
const [request, setRequest] = React.useState([])
空数组没有元素,因此这会将undefined
记录到控制台:
console.log(request[0])
然后这会产生一个错误:
console.log(request[0]["question"])
然后这不会产生错误,因为它没有被执行,因为它之前的行产生了错误:
console.log(requst[0].question)
但是如果执行了那行代码,它也会产生错误。
您为填充状态而获取的数据来自异步操作。 所以它会在以后的某个时间发生。 (可能是几毫秒,感觉是瞬间的,但还要晚一些。)
在获取该数据并更新状态之前,代码需要能够处理空数组的初始状态。 可选链接是一种选择:
console.log(requst[0]?.question)
或者也许将整个事情包装在一个条件中:
if (request.length > 0) {
console.log(request[0]);
console.log(request[0]["question"]);
console.log(requst[0].question);
}
您更喜欢如何处理空数组取决于您和您正在实现的逻辑。 但关键是,由于您定义了一个空数组,因此代码应该期望以一个空数组开头。
在request
状态中设置数据需要时间。 因此, console.log(request[0])
的第一个日志总是undefined
,其他两个 console.logs 总是出错。
在这种情况下,您可以使用UseEffect
挂钩进行检查。
useEffect(() => {
if(request.length === 0) return;
console.log(request[0]); // returns the first object array
console.log(request[0]['question']);
console.log(requst[0].question);
}, [request]);
如果你不想使用useEffect
,你可以使用?
无错误地访问对象属性。
console.log(request[0]);
console.log(requst[0]?.question);
if (request !== undefined && request.length > 0) {
console.log(request[0])
console.log(request[0]["question"])
console.log(request[0].question)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.