【发布时间】:2021-07-10 03:54:19
【问题描述】:
我在componentDidMount中有以下内容
componentDidMount() {
const company = this.props.location.state.company;
const financials = this.props.location.state.financials;
let { values } = this.state;
values = EDITABLES.map((data) => { //EDITABLES is a const imported array
return {
id: data.id,
name: data.name,
value: financials[data.id]
newValue: "",
};
});
this.setState({
values,
});
}
但是,如果我在渲染时 console.log values,第一个控制台日志将其显示为未定义,但下一个将其显示为已定义。我也可以在我的渲染方法中 map values 没有任何问题。
render() {
const {
company,
financials,
values,
} = this.state;
console.log(values, "check")
我的问题是在我的渲染方法中,我调用了一个函数{this.calculate(financial.id)}
calculate(financial) {
const { financials, values } = this.state;
console.log(values, "values");
let numerator;
if (financial === "tev_profit") { //this line is okay
let tev = values.find(o => o.id === "total_value");
console.log(tev, "here");
numerator = tev.newValue; //this line is causing error.
从控制台日志看来,tev 有时已定义,但有时未定义。我不确定我哪里出错了,因为我也将它添加到我的代码中,但仍然面临相同的 typeError:
this.calculate = this.calculate.bind(this);
更新:
在进入任何其他 if 块之前,我曾尝试将 if(values) 添加到我的 calculate 函数中,但得到相同的错误
【问题讨论】:
标签: javascript reactjs