是否可以在其他功能标签上设置状态?

Is it possible to setState on other function tag?

这是我的代码,

此代码运行良好,使用“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 正在运行, 但它不适用于我自己的功能标签

知道如何修复它 非常感谢。

您已将无条件状态更改放入渲染中。因此,您的渲染会触发状态更改,而状态更改会触发重新渲染,重新渲染会再次触发状态更改 - 无限循环。

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

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>
      )
   } 
}