我正在嘗試更新串列中的每個答案,以便我可以將每個答案傳遞給 redux 并將所有答案發送給 API。
我試圖將每個答案作為變數傳遞,并將其分配給陣列中的狀態。我真的很困惑。
const DATA = [{
id: '1',
title: 'Do you feel appropriately rewarded for your work?',
},
{
id: '2',
title: 'Are you happy with your working hours?',
},
{
id: '3',
title: 'Do you feel recognised when you do something well?',
},
{
id: '4',
title: 'Do you have enough information to do your job well?',
},
{
id: '5',
title: 'Do you have the resources you need to do your job well?',
},
{
id: '6',
title: 'Do you feel empowered to make decisions?',
},
];
const [data, setData] = useState('');
let newData = [...data];
const questionIndex = newData.findIndex((q, i) => q.id == idVariable);
if (questionIndex > -1) newData[questionIndex].answer = answerVariable;
const handleSubmit = () => {
navigation.navigate('SplashScreen')
setData(newData);
console.log("hey", newData)
}
uj5u.com熱心網友回復:
import React, { useEffect, useState } from "react";
const data = [{
id: '1',
title: 'Do you feel appropriately rewarded for your work?',
},
{
id: '2',
title: 'Are you happy with your working hours?',
},
{
id: '3',
title: 'Do you feel recognised when you do something well?',
},
{
id: '4',
title: 'Do you have enough information to do your job well?',
},
{
id: '5',
title: 'Do you have the resources you need to do your job well?',
},
{
id: '6',
title: 'Do you feel empowered to make decisions?',
},
];
uj5u.com熱心網友回復:
應該是這樣的,請嘗試,因為 setState udate asych 方式不會立即得到結果
const [questions, setQuestions] = useState(DATA)
const handleSubmit = () => {
setQuestions((prevState) => {
const questionIndex = prevState.findIndex((question) => question.id === idVariable)
if (questionIndex > -1) {
questions[questionIndex].answer = answerVariable;
}
return questions;
});
navigation.navigate('SplashScreen')
console.log("hey", newData)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/419149.html
標籤:
