首页 > 解决方案 > 如何在渲染前修改数组

问题描述

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

谢谢

标签: react-nativereact-redux

解决方案


我看你的代码,我发现你在循环中设置状态,它会影响你的应用程序性能。我修改如下

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


推荐阅读