2017-10-16 129 views
0

我試圖setSatecomponentDidMount()但狀態沒有變化。我聲明瞭狀態,如下:React Native componentDidMount中的setState不起作用

constructor(props) { 
    super(props); 
    this.state = { 
     links: [], 
     personalInfo: { 
     name: "", 
     phone: "", 
     email: "", 
     address: { 
      city: "", 
      state: "", 
      country: "", 
     }, 
     }, 

     statement: "", 
     editMode: false, 
     superEditMode: false, 
    } 
    } 

而且我componentDidMount是如下:

componentDidMount() { 
    if (this.props.data) { 
     this.props.data.personalInfo ? this.setState({personalInfo: this.props.data.personalInfo}) : null 
     this.props.data.address ? this.setState({address: this.props.data.address}) : null 

     //this.props.data.links ? this.setState({links: this.props.data.links}) : null 
     //console.log((this.props.data.links ? true : false)); 
     this.setState({links: [ 
     { 
      linkType: "Portfolio", 
      linkAddress: "www.johndoe.com", 
     }, 
     { 
      linkType: "Github", 
      linkAddress: "https://github.com/johndoe", 
     }, 
     { 
      linkType: "LinkedIn", 
      linkAddress: "https://linkedin.com/johndoe", 
     }, 
     ]}); 
     console.log(this.state.links); 
     this.props.data.statement ? this.setState({statement: this.props.data.statement}) : null 
    } 

這是非常奇怪的是,this.state.personalInfothis.state.addressthis.state.statement被設置爲新州從props如預期,但this.state.links仍然是最初的狀態。

+0

setState是異步的。如果您在正常之後沒有看到console.log。使用回調。 – bennygenel

回答

1

每當您調用狀態更改的setState時,您都會強制重新渲染。所以,我推薦做的第一件事是重構你的代碼,這樣你只需要調用setState一次...

其次,如果你認爲它沒有改變你的鏈接狀態,因爲console.log(this.state.links)仍然顯示一個空的數組,這可能是因爲在執行該行時,狀態尚未更新。 setState是異步的。試試這個...

if (this.props.data) { 
    const { personalInfo, address, links, statement } = this.props.data; 
    this.setState({ 
     personalInfo: personalInfo || null, 
     address: address || null, 
     links: links || null, 
     statement: statement || null, 
    },() => { 
     const { personalInfo, address, links, statement } = this.state; 
     console.log({ personalInfo, address, links, statement }); 
    }) 
} 
相關問題