我创建相同的组件(配方(或屏幕两次,发送不同的属性。
<Recipes setRecipes = {this.setRecipes} id="1" />
<Quantity setQuantity = {this.setQuantity} />
<Recipes setRecipes = {this.setRecipes2} id="2" />
<Quantity setQuantity = {this.setQuantity} />
属性函数如下所示。只有状态会改变。
setRecipes = (recipe) => {
this.setState({recipe:recipe})
}
setRecipes2 = (recipe2) => {
this.setState({recipe2:recipe2})
}
在名为 Recipes 的 mty 组件中,我定期获取我的本地数据库(我使用 pouchdb(、我的食谱和产品。
import React, { Component } from 'react';
import { Text, View, TouchableOpacity, ScrollView } from 'react-native';
import style from './Styles/styleNew';
import PouchDB from 'pouchdb-react-native';
PouchDB.plugin(require('pouchdb-find'));
const gThis = null;
const db = new PouchDB('X')
export default class Recipes extends Component {
constructor(props) {
super(props);
gThis = this;
this.state = {
setRecipes: this.props.setRecipes,
id: this.props.id,
recipeID: null,
options: [ ],
};
}
getRecipes() {
let data = []
db.find({
selector: {
type: {
"$eq": this.state.id,
},
owner: {
"$in": ['user']
},
},
}).then(function (recipes) {
recipes = recipes.docs
for (let i = 0; i < recipes.length; i++) {
recipe = recipes[i]
let current = {
id: recipe._id,
name: recipe.name,
recipe: recipe,
}
data.push(current)
}
gThis.setState({ options: data })
}).catch(function (err) {
console.warn(err.toString())
});
}
componentDidMount() {
this.getRecipes()
}
handleBackPress = () => {
this.props.navigation.goBack();
}
defineRecipe(recipe, index) {
this.setState({ recipeID: recipe._id });
this.state.setRecipes(recipe)
}
render() {
return (
<View style={{ flex: 1 }}>
<Text style={style.listText}>RECIPES {this.state.id} </Text>
<ScrollView style={style.listScroll}>
{this.state.options.length >0 &&
this.state.options.map((item, index) => {
key = index + '-' + this.state.id
//key = new Date().toISOString()
console.log(key)
return (
<TouchableOpacity
style={this.state.recipeID === item.id ? style.listOptionSelected : style.listOption}
onPress={() => { this.defineRecipe(item.recipe, index);}}
key={key} >
<Text style={style.listOptionText}>{item.name}</Text>
</TouchableOpacity>
);
})
}
</ScrollView>
</View>
);
}
}
但是第二个屏幕配方被渲染了两次。
渲染 1
渲染 2
如您所见,内容被替换。
我认为这可能与您有关 gThis 我认为这是一个全局的这个?
尝试在类成员中访问它的更好方法是在类中使用词法箭头函数,如下所示:
getRecipes = () => {
// implementation
}
或者在构造函数中将类成员绑定到此类,如下所示
constructor(props) {
super(props);
gThis = this;
this.state = {
id: this.props.id,
recipeID: null,
options: [ ],
};
this.getRecipes = this.getRecipes.bind(this);
this.defineRecipe = this.defineRecipe.bind(this);
}
在不同的节点上,据我所知,你有 babel 转译你的 ES6 代码。我强烈建议将 for 循环替换为 es6 变体,例如地图或 forEach 以提高可读性
const options = recipes.map(recipe => {
const { _id: id, name } = recipe;
data.push({
id,
name,
recipe,
});
});
this.setState({ options });