我创建了一个测验应用程序,它有问题和选项。首先,我映射了问题,并在映射中映射了属于该问题的选项。每个选项都有自己的 onClick 事件处理程序来设置答案,并且该事件处理程序将答案发送到服务器。但问题是事件处理程序发送了两次请求。原因一定是使用嵌套映射创建的元素,但我还没有找到任何解决方案。 这是代码的一部分:
let questions = null
if (this.props.questions) {
questions = this.props.questions.map((question, index) => {
return (
<div className={classes.Question} key={question.id}>
<p>{`${index + 1}) ` + question.value}</p>
{question.options.map((option, optionIndex) => {
return (
<label onClick={question.clicked ? null : () => this.props.onSetQuestionAnswer(...params)} key={optionIndex}>{option.value}
<input type="radio" name="radio" />
</label>
)
})}
</div>
)
})
}
点击事件 Action 创建者
export const setOptionForQuestion = (...params) => {
return async dispatch => {
try {
const { data } = await axios.post(`endpoint`, {
..body
})
if (data.success) {
dispatch({
type: actionTypes.SET_ANSWER_OPTION,
...dataToReduxStore
})
}
} catch (error) {
dispatch({
type: actionTypes.SET_ANSWER_OPTION_ERROR
})
}
}
}
最佳答案
您可以尝试调用 event.preventDefault()
export const setOptionForQuestion = (...params,e) => {
e.stopPropagation()
e.preventDefault()
// rest of the code
}
关于javascript - 如何防止嵌套映射元素触发 onClick 事件两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52219758/