【发布时间】:2021-06-04 07:38:56
【问题描述】:
这是我的代码,
此代码运行良好,使用“setState”在 componentDidMount 标签中设置新变量。
export default class App extends React.Component {
constructor(props){
super(props);
this.state = {
name: "peter",
}
}
componentDidMount(){
this.setState({name:"sam"});
}
render(){
return (
<View>
<Text>
{this.state.name}
</Text>
</View>
)
}
}
但我想创建一个新函数来设置它。
export default class App extends React.Component {
constructor(props){
super(props);
this.state = {
name: "peter",
}
}
changename(){
this.setState({name:"sam"});
}
render(){
this.changename();
return (
<View style={styles.container}>
<Text style={styles.paragraph}>
{this.state.name}
</Text>
</View>
)
}
}
显示
Minified React error #185;
错误
componentDidMount 是工作, 但它不适用于我自己的功能标签
知道如何解决它 非常感谢。
【问题讨论】:
-
你不应该在
render中调用setState——这可能会造成无限的重新渲染循环。
标签: react-native setstate