[英]React Component rendering but not mounting thus unable to setState
我有一個名為 FillForm 的功能組件,它調用要在 FormFiller function 中按順序呈現的對象列表。 這些組件正在正確渲染和顯示,但是當試圖讓它們更改其內部 state 時出現錯誤
警告:無法在尚未安裝的組件上調用 setState。 這是一個無操作,但它可能表明您的應用程序中存在錯誤。 相反,直接分配給
this.state
或定義一個state = {};
class 屬性在 MultipleChoiceQuestion 組件中具有所需的 state。
這是表格填寫器 function:
const FillForm = props => {
return (
<div className={classes.container} key={1}>
<p>Form Filler</p>
{formElements[currentPage].map((Element => (
Element.render()
)))}
<Button variant="contained" disabled={backDisabled} onClick={handleBack}>BACK</Button>
<SubmitButton />
</div>
)
}
我已經刪除了與這里的問題無關的代碼,但是 formElements 都是我的 BaseElement 的子元素,而 formElements object 是上述 class 需要按順序呈現的對象的列表。
import React from "react"
class BaseEntry extends React.Component {
constructor(props) {
super(props);
this.key = 0
this.type = ""
}
setID(id) {
this.key = id;
}
setType(type) {
this.type = type;
}
userResponse() {
return (null);
}
//This should always be overridden
render() {
return (
<React.Fragment>
<div></div>
</React.Fragment>
)
}} export default BaseEntry;
以下是當我嘗試在多項選擇題中對 select 進行不同選擇時給我帶來問題並給出錯誤的代碼。
class MultipleChoiceQuestion extends BaseEntry {
constructor(question_text, choices) {
super();
this.question_text = question_text //A string
this.choices = choices // [[1, "Choice text"], [2, "Choice text two"]]
this.response = 1
this.handleChange = this.handleChange.bind(this)
this.state = {response: 1}
}
userResponse() {
return ({
"id" : this.id,
"response" : this.response,
"type" : this.type
})
}
componentDidMount() {
console.log("mounted")
}
handleChange(e) {
console.log(e.target.value)
this.setState({response: e.target.value})
}
render() {
return (
<React.Fragment key={this.key}>
<div>
<h2>{this.response}</h2>
<FormControl component="fieldset">
<RadioGroup aria-label={this.question_text} value={this.response} name={this.question_text} onChange={this.handleChange}>
{this.choices.map(((choice, index) => (
<FormControlLabel value={choice[0]} control={<Radio />} label={choice[1]} key={index}/>
)))}
</RadioGroup>
</FormControl>
</div>
</React.Fragment>
);
}
}
export default MultipleChoiceQuestion;
這是代碼框:[https://codesandbox.io/s/priceless-leavitt-yh5dp?file=/src/FillForm.js]
render() {
return (
<React.Fragment key={this.key}> {/* remove key form here as your component dosen't have it */}
<div>
<h2>{this.state.response}</h2> {/* here is the problem use `this.state.resopnse` instead of `this.response` */}
<FormControl component="fieldset">
<RadioGroup aria-label={this.question_text} value={this.response} name={this.question_text} onChange={this.handleChange}>
{this.choices.map(((choice, index) => (
<FormControlLabel value={choice[0]} control={<Radio />} label={choice[1]} key={index}/>
)))}
</RadioGroup>
</FormControl>
</div>
</React.Fragment>
);
}
您在渲染 function 中使用this.response
您應該改用this.state.response
。 並從片段中刪除this.key
,因為您的組件沒有。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.