reactjs - 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 应该可以解决这个问题,但它现在是遗留问题。如何解决?
解决方案
如果我们假设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
错误。
推荐阅读
- python - asyncio.wait 的替代方案?
- cython - Cython 编译警告不兼容类型
- ios - Appcenter iOS 安装错误“无法安装此应用,因为无法验证其完整性”
- sql-server - 如何调用表中每一行的过程并将结果写入新列?
- python - 带有重复的 Python 排列
- postgresql - 优化与 lpath 相关的查询的问题
- heroku - 将 Heroku 应用程序连接到 Ionos 域名
- python - lstm 输出的串联
- vba - VBA从另一个Word文档中的指定位置复制到Word中的一个文档(包括)
- c++ - c++) 将一维数组放入二维数组时出现错误