猿问

为什么 this.setState() 在构造函数中不起作用?

我正在使用react.js,并this.setState()在构造函数中添加了它,但它不起作用。这是我的代码 -


class App extends React.Component {

  constructor(props) {

    super(props);

    this.state = {

      age: '18'

    }

    this.setState({id: 'name'}); 

  }

  render(){

    return (

      <div>

        <p>{this.state.id}</p>

        <p>{this.state.value}</p>

      </div>

    )

  }

}

这会渲染第二个p标签,但不会渲染第一个标签,为什么会这样?


富国沪深
浏览 166回答 3
3回答

智慧大石

setState 函数除了设置状态外,还具有更改时重新渲染的机制。构造函数在组件实际安装之前执行,并且不会渲染任何内容。这就是为什么在构造函数中使用 setState 没有意义。所以你需要像这样实现这一点:constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.state = {&nbsp; &nbsp; &nbsp; age: '18',&nbsp; &nbsp; &nbsp; id: 'name'&nbsp; &nbsp; }&nbsp; }

喵喵时光机

不要使用setState()内部构造函数或内部渲染方法构造函数- 在创建实例时调用一次,如果您在构造函数内部创建,则不会发生重新渲染。render - 如果您setState()在 render 方法内部使用,它将变为无限,因为当您使用时会发生重新渲染setState()如果你想保存这样的属性来声明在生命周期方法中执行它componentDidMount()改进class App extends React.Component {&nbsp; constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.state = {&nbsp; &nbsp; &nbsp; age: '18'&nbsp; &nbsp; }&nbsp; }&nbsp; componentDidMount(){&nbsp; &nbsp; this.setState({id: 'name'});&nbsp;&nbsp; }&nbsp; render(){&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <p>{this.state.id}</p>&nbsp; &nbsp; &nbsp; &nbsp; <p>{this.state.value}</p>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; )&nbsp; }}或者像年龄一样直接输入&nbsp;this.state = {&nbsp; &nbsp; &nbsp; age: '18',&nbsp; &nbsp; &nbsp; id: 'name'&nbsp;}

梵蒂冈之花

class App extends React.Component {&nbsp; constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.state = {&nbsp; &nbsp; &nbsp; age: '18',&nbsp; &nbsp; &nbsp; id: '',&nbsp; &nbsp; }&nbsp; }componentDidMount(){&nbsp;this.setState({id: 'name'});&nbsp;}&nbsp; render(){&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <p>{this.state.id}</p>&nbsp; &nbsp; &nbsp; &nbsp; <p>{this.state.age}</p>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; )&nbsp; }}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答