React State For Many Items



用户在70个问题中选择四个选项中的一个。四个选项永远不会改变但我需要知道每个问题都选了哪个。下面的代码工作,但我试图确定我是否应该复制这个代码70次,或者是否有更好的方法?谢谢!


const [selected, setSelected] = useState({
option1: {
title: "I can think of where this has lead me",
selected: false,
},
option2: {
title: "I can think of how this has changed me",
selected: false,
},
option3: {
title: "I can think of how I overcame this",
selected: false,
},
option4: {
title: "This has an interesting backstory",
selected: false,
},
});
const selectingOption1 = () => {
setSelected({
...selected,
option1:{selected: true,
title: "I can think of where this has lead me" }
})
}

显示问题示例:

<Card onClick={props.selectingOption1}  className={classes.itemCard}>
<img className={classes.iconImg} src='/item1.png' />
<p> I can think of where this has lead me</p>
</Card>

我将为options创建一个组件,并将其导入到该组件中。然后你可以用道具给出选项。在新组件中,你只需要选项部分的一个状态

const [selected, setSelected] = useState({ title: "", selected: false })

不,你不需要复制70次相同的代码。

您可以通过定义带有选项的70个问题数组来获得它。

你可以参考以下步骤。

你可以用4个选项定义问题的数据结构。

注意,question对象具有id属性作为唯一键来标识问题。


{
id: 1,
title: 'Question 1',
options: {
option1: {
title: "I can think of where this has lead me",
selected: false,
},
option2: {
title: "I can think of where this has lead me",
selected: false,
},
}
}

然后你可以为70个问题定义一个状态变量,并将其设置在useEffect或任何地方。也许你可以从props中获取它,或者将其定义为常量数组。

const [questions, setQuestions] = useState<any>([]);
useEffect(() => {
// some API call to get questions
// We assume like the following:
const questions = [
{
id: 1,
title: 'Question 1',
options: {
option1: {
title: "I can think of where this has lead me",
selected: false,
},
option2: {
title: "I can think of where this has lead me",
selected: false,
},
}
}
];
setQuestions(questions);
}, [])

定义一个函数来选择一个有2个参数的选项第一个参数是问题ID,第二个参数是选项ID。

const selectOption = (questionId, optionKey) => {
setQuestions((prev) => {
const newData = [...prev];
const q = newData.find(x => x.id === questionId);
if (q) {
q.options = {...q.options, [optionKey]: true};
}
return newData;
});
}
<<p>

渲染方法/strong>我基本上做了一个渲染函数,你可以分解更多。

你可以让Question组件和Options呈现4个选项。

return (
<>
{questions.map((question) => (
<Card key={question.id} question={question}  className={classes.itemCard}>
<img className={classes.iconImg} src='/item1.png' />
<p> {question.title}</p>
{Object.keys(question.options).map((optionKey) => (
<div key={optionKey} onClick={selectOption(question.id, optionKey)}>{question.options[optionKey].title}</div>
))}
</Card>
))}
</>
)

最新更新