【问题标题】:Is it possible to setState on other function tag?是否可以在其他功能标签上设置状态?
【发布时间】: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


【解决方案1】:

您已在渲染中进行了无条件的状态更改。因此,您的渲染会触发状态更改,从而触发重新渲染,从而再次触发状态更改 - 无限循环。

您可以设置某种条件来触发状态更改,例如:

export default class App extends React.Component {
  constructor(props){  
        super(props);  
        this.state = {name: "peter"}  
    }

    changename(){ this.setState({name:"sam"}); }
    
    render(){
      if(this.state.name==='peter')
        this.changename();

      return (
        <View>
          <Text>{this.state.name}</Text>
        </View>
      )
   } 
}

【讨论】:

    猜你喜欢
    • 2020-08-30
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-20
    • 2015-07-07
    • 1970-01-01
    相关资源
    最近更新 更多