[英]How to call other constructors when re-rendering with setState in reactJS?
我在組件中有這些構造函數。 這里的想法是讓按鈕具有onClick屬性,當單擊按鈕時,onItemClick()函數將調用該函數,如果單擊右鍵,則this.state.index會增加1。
這里的問題是狀態會更改,但是不會再次調用其他構造函數,因此組件中不會發生任何更改。
問題是每次狀態更改時如何調用這些構造函數? 還是應該重新編寫代碼,使其背后的邏輯保持不變,這意味着每次狀態更改時,我都會獲得所有取決於狀態的新信息?
constructor() {
super()
this.state = {
index: 1,
}
this.currentQ = data[this.state.index]
this.answers = Object.values(this.currentQ.answers).map((item, index) => {
return <button onClick={() => this.onItemClick(index)}>{item}</button>
})
}
編輯:提供下面組件的完整代碼。 感謝您的回答!
import React, { Component } from 'react';
import {data} from './input.js';
class Card extends Component {
constructor() {
super()
this.state = {
index: 1,
}
this.currentQ = data[this.state.index]
this.answers = Object.values(this.currentQ.answers).map((item, index) => {
return <button onClick={() => this.onItemClick(index)}>{item}</button>
})
}
onItemClick = (index) => {
let rightAnswer = this.currentQ.rightAnswer
let userGuess = Object.keys(this.currentQ.answers)[index]
rightAnswer === userGuess ? this.setState({index: this.state.index += 1}) : console.log('false')
}
render() {
return (
<div>
<h2>{this.currentQ.engWord}</h2>
{this.answers}
</div>
)
}
}
export default Card;
構造函數僅調用一次,並且不應包含任何副作用或在其中查看計算。 每次狀態更改時, render()
函數都會被調用,因此最好將answers
放在那里。 關於currentQ
,從代碼中還不清楚,但是也許它應該是狀態的一部分。 如果變化很大,並且組件視圖可能依賴於它。 為了更好地決定什么應該成為組件狀態的一部分,請參閱《 React中的思考》 。
這是Dan Abramov撰寫的React組件生命周期的示意圖
從提供的有限代碼來看,@ balabis似乎只想根據狀態變化來計算一些類成員。 因此, componentDidUpdate
生命周期方法將是一個不錯的選擇。
碼
componentDidUpdate(prevProps, prevState){
this.currentQ = data[this.state.index]
this.answers = Object.values(this.currentQ.answers).map((item, index) => {
return <button onClick={() => this.onItemClick(index)}>{item}</button>
})
}
注意:初始渲染不會調用componentDidUpdate
。 有關更多信息-https://reactjs.org/docs/react-component.html#componentdidupdate
嘗試使用componentShouldMount(){}函數並嘗試對此進行更新。 即使我也面臨同樣的問題,但是這樣對我有用。 而且不要直接設置值,請使用setState() -我工作過Mobx 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.