我在setSate
尝试componentDidMount()
,但状态并未改变。我宣布州如下:
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
仍然是最初的州。
答案 0 :(得分:1)
每次使用状态更改调用setState时,都会强制重新渲染。所以,我建议做的第一件事就是重构你的代码,这样你只需调用一次setState ......
其次,如果您认为它没有改变您的链接状态,因为var label = jQuery('.colored').html();
console.log( label ); // outputs Unicorn
仍然显示一个空数组,那可能是因为该行执行时,州尚未更新。 setState是异步的。试试这个......
console.log(this.state.links)