[英]Single function for state change no multiple states whit similar name
I'm trying to create a function for the state change, on multiple states ... 我正在尝试为多个状态创建状态更改的函数...
I have the following states in the constructor()
我在
constructor()
具有以下状态
this.state={
answer1:"",
answer2:"",
answer3:"",
answer4:"",
answer5:"",
//answerN... (25 to be exact)
}
I have this Question component which is a <p>
tag and 6 radio buttons for the question answers 我有这个Question组件,它是一个
<p>
标签和6个单选按钮,用于回答问题
I make 5 instances of this component 我制作了该组件的5个实例
<Question addAnswer={this.addAnswer} title="...." />
<Question addAnswer={this.addAnswer} title="..." />
....
each calling the same function named addAnswer()
每个调用相同的名为
addAnswer()
函数
addAnswer = (answerValue) => {
this.setState({answer1:answerValue},()=>console.log(this.state.answer1))
}
this function will change only the answer1 state
此功能将仅更改
answer1 state
So how to make it something like this to work 那么如何使它像这样工作
addAnswer = (answerNumber,answerValue) => {
this.setState({ answer + answerNumber: answerValue },()=>console.log(this.state.answer + answerNumber))
}
Is function like this possible? 这样的功能可能吗?
Is there an option of making the answer state an Array and how will I determine which index of this array is answered and on later changed ??? 是否有将答案状态设置为数组的选项,我将如何确定该数组的哪个索引得到了答复并在以后进行了更改?
I prefer to pass the whole name of the attribute as a parameter to the function, instead of just a number. 我更喜欢将属性的全名作为参数传递给函数,而不仅仅是数字。 I think it looks more readable and easy to understand.
我认为它看起来更具可读性和易于理解。
Like this: 像这样:
addAnswer = (answerCode, answerValue) => {
this.setState({ [answerCode]: answerValue }, () =>
console.log(this.state[answerCode])
)
}
If I were you I would probably change the structure to look something like this: 如果我是你,我可能会更改结构,使其看起来像这样:
{
"answers": {
1: {
"code": 1,
"value": "Yes"
}
}
}
Then, when you are passing the value to the reducer, you can pass the whole answer object: 然后,当您将值传递给减速器时,可以传递整个答案对象:
{
"code": 2,
"value": "No"
}
And to add a new answer: 并添加一个新答案:
addAnswer = (answer) => {
this.setState({ [answer.code]: answer })
}
I'd suggest you to iterate over some data array, which holds eg titles : 我建议您遍历一些数据数组,其中包含例如titles :
someArray.map((title, i) => (
<Question addAnswer={() => this.addAnswer(answerValue, i)} title={title} />
);
Then you will be able to reference to an item on specified index i
. 然后,您将可以引用指定索引
i
上的项目。
addAnswer = (answerValue, i) => {
this.setState({ `answer${i}`: answerValue });
};
Note : You didn't specify from where answerValue
prop comes from + i
starts at 0
. 注意 :您没有指定
answerValue
来源+ i
从0
开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.