如何使用 onClick 防止我的数组重复洗牌



我需要你新鲜的眼睛来帮助我。

我的数组中有一组答案,我在第一次渲染时洗牌。

我在这里的问题是,我知道如果我单击其中一个答案,setState 将重新渲染并因此重新洗牌我不想要的数组。

你可以在下面看看我的代码:

export default class extends React.Component {
constructor(props) {
super(props)
this.state = {
user: this.props.user,
token: this.props.token,
data: this.props.data,
count: 0,
select: undefined
}
this.changeQuestion = this.changeQuestion.bind(this);
this.onCorrect = this.onCorrect.bind(this);
this.onFalse = this.onFalse.bind(this);
}
static async getInitialProps({req, query}) {
const id = query.id;
const authProps = await getAuthProps(req, 'Country/Questions?theory=' + id)
return authProps
}
componentDidMount() {
if (this.state.user === undefined) {
Router.push('/login')
}
}
changeQuestion() {
this.setState({
count: this.state.count + 1,
select: undefined
})
}
onCorrect() {
this.setState({
select: true
})
}
onFalse() {
this.setState({
select: true
})
}
mixAnswers() {
const answer = this.props.data.Properties.Elements
const answers = answer[this.state.count].Properties.Answers
const answersObj = answers.reduce((ac, el, i) => {
ac.push(
<p key={i} onClick={i === 0
? this.onCorrect
: this.onFalse} className={i === 0
? 'exercices__answers--correct'
: 'exercices__answers--false'}>{el}</p>
)
return ac
}, [])
const answersShuffled = answersObj.sort(() => 0.5 - Math.random())
return answersShuffled;
}


render() {
const {user, token, data} = this.state
const answer = this.props.data.Properties.Elements
const answers = answer[this.state.count].Properties.Answers
return (
<div>
{user !== undefined
? <Layout user={this.state.user}>
<div>
{answer[this.state.count].Properties.Sources !== undefined
? <img src={answer[this.state.count].Properties.Sources[0].URL}/>
: ''}
<h1>{answer[this.state.count].Properties.Question}</h1>
{this.mixAnswers().map((el, i) => <p key={i} onClick={el.props.onClick} className={this.state.select !== undefined
? el.props.className
: ''}>{el.props.children}</p>)
}
<p>{answer[this.state.count].Properties.Description}</p>
</div>
<button onClick={this.changeQuestion}>Next Question</button>
</Layout>
: <h1>Loading...</h1>}
</div>
)
}
}

显然,我使用"this.mixAnswers(("方法的方式是问题所在。我怎样才能防止它重新渲染然后重新洗牌这一系列问题。 PS:不要关注onCorrect((和onFalse((。

你应该确保只调用一次随机答案的逻辑,你可以在 ComponentWillMount 或 ComponentDidMount 上获得此行为,然后将它们保存在组件的状态和渲染函数中,而不是

{this.mixAnswers().map((el, i) => <p key={i} onClick={el.props.onClick} className={this.state.select !== undefined
? el.props.className
: ''}>{el.props.children}</p>)
}

您使用this.state.answers.map()...

最新更新