首页 > 解决方案 > React:在渲染之前生成对象数组以避免更改不受控制的输入错误

问题描述

我需要根据初始状态的货币和 priceLists 填充“productPrices”数组

  constructor(props) {
    super(props);
    this.state = {
     currencies:["EUR","DKK"],
     priceLists:["basic","extended"],
     productPrices:[]
    }
    }

喜欢以下

this.state = {
 currencies:["EUR","DKK"],
 priceLists:["basic","extended"],
 productPrices:[{currency:"EUR",priceLists:"basic",productPrice:0},
                {currency:"DKK",priceLists:"basic",productPrice:0},
                {currency:"EUR",priceLists:"extended",productPrice:0},
                {currency:"DKK",priceLists:"extended",productPrice:0},
               ]
}

我通过 componentDidMount 填充“productPrices”,这导致“更改要控制的整数类型的不受控输入”,因为在尚未定义数组中的对象的初始渲染之后调用 componentDidMount。我猜 componentWillMount 应该可以解决这个问题,但它现在是遗留问题。如何解决?

标签: reactjs

解决方案


如果我们假设productPrice由 api 调用填充。在render函数内部,我们可以进行检查以检测 api 调用何时完成,您的代码将如下所示:

componentDidMount(){
    this.setState({loading: true});
    apiCallFunction().then((response) => {
        // Your processing for the `productPrice` property
        this.setState({loading: false});
    });
}

render(){
    if(this.state.loading){
        return (<Spinner // css spinner/>)
    } else {
        return // your component that you currently have. 
    }
}

这将避免changing an uncontrolled input of type integer to be controlled错误。


推荐阅读