我想根据另一个状态值设置一个状态值。也有类似的问题。但是他们都不满足我的需求。
所以,这是我的代码
import React, { Component } from 'react';
class Form extends Component {
state = {}
constructor(props) {
super(props);
this.state = {
a: "somevalue",
b: this.someFunc()
};
}
someFunc(){
if(this.props.value=="something"){
return "value1"
}else{
return "value2 "+this.state.a;
}
}
render() {
return (<h1>{this.state.b}</h1>
);
}
}
export default Form;
因此,此处的输出为 value2 undefined 。我希望它值2个值。我该如何实现?
答案 0 :(得分:0)
您应该使用生命周期方法来更新状态属性b
。
componentDidMount() {
this.setState({
b: someFunc()
})
}