如何在渲染之前修改数组

蒂博汗

我想更改数组的值以在渲染之前显示新数组。我首先使用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组件中,我实际上得到了数据,我可以得到我尝试发送新数组的第一个未修改的数组的值,因为另一个视图可能需要使用异步操作?

谢谢

雷诺阿罗德

我看一下您的代码,发现您处于setState循环中,它将影响您的应用程序性能。我如下修改

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})}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章