react-native - 如何在渲染前修改数组
问题描述
我想更改我的数组的值以在渲染之前显示新数组。我首先使用 componentWillMount 调用我的函数。我的函数改变函数中的数组
import recipeData from '../Helpers/RecipeData'
componentWillMount(){
this._selectRicipe()
}
constructor(props) {
super(props)
this.state = {
myRecipeData: recipeData
}
}
_selectRicipe(){
for (let i = 0; i < recipeData.length; i++) {
for (let j = 0; j < this.props.listIngredients.length; j++) {
if (this.props.listIngredients[j].name == recipeData[i].type) {
newData = []
console.log(this.props.listIngredients[j].name)
newData = recipeData[i].name
this.setState({ myRecipeData: newData })
console.log("new RecipeData 1 : " + this.state.myRecipeData[i].name)
}
}
}
}
render() {
console.log("..New..recipe.. " + this.state.myRecipeData[0].name);
return (
<FlatList
data={this.state.myRecipeData}
keyExtractor={(item) => item.id.toString()}
renderItem={({ item }) => <RecipeDesc recipeData={item} />}
>
</FlatList>
)
}
在我的 RecipDesc 组件中,我得到了数据,事实上我可以得到第一个未修改数组的值,我试图发送新数组,因为另一个视图可能需要使用异步操作?
谢谢
解决方案
我看你的代码,我发现你在循环中设置状态,它会影响你的应用程序性能。我修改如下
constructor(props) {
super(props)
this.state = {
myRecipeData: recipeData
}
}
//please do it in the componentDidMount
componDidMount() {
this._selectRicipe()
}
_selectRicipe(){
let newData = [] // avoid to define a object in the loop repeately
for (let i = 0; i < recipeData.length; i++) {
for(let j = 0; j < this.props.listIngredients.length; j++){
if(this.props.listIngredients[j].name == recipeData[i].type){
console.log(this.props.listIngredients[j].name)
newData.push(recipeData[i].name)
// the flatlist neeed data is arry and not loop to
// setState
// this.setState({ myRecipeData: newData })
console.log("new RecipeData 1 :
"+this.state.myRecipeData[i].name)
}
}
}
this.setState({ myRecipeData: newData }) }
推荐阅读
- perl - 使用 perl 更改时间戳的格式
- python - 我的矢量化项目不起作用。我将如何解决这个问题
- javascript - 我无法在 prisma 架构问题中部署更改
- php - 如何在 Magento 2 中创建带有产品编辑页面下拉菜单的自定义按钮?
- rust - 如何在不使用第三方库的情况下对除第一个和最后一个元素之外的向量进行洗牌?
- c - 在 C 中使用 2D 数组进行简单 I/O 时变量值发生变化,导致分段错误
- javascript - Django 在 ajax 中回复评论不起作用
- maven - 如何将maven项目创建为其他项目的依赖jar而不依赖于其他项目
- java - Navigation Drawer Activity:在片段之间传递值
- html - Bootstrap Grid 不会填满空的地方