0
我試圖setSate
componentDidMount()
但狀態沒有變化。我聲明瞭狀態,如下: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.personalInfo
this.state.address
this.state.statement
被設置爲新州從props
如預期,但this.state.links
仍然是最初的狀態。
setState是異步的。如果您在正常之後沒有看到console.log。使用回調。 – bennygenel