我从React Native Playground尝试了以下示例(Fading Hearts): https://rnplay.org/apps/CkBOBQ
该示例使用createClass
语法编写。我将相同的语法转换为ES6语法,我使用了类和方法。该应用程序正确编译并打开,但是当我点击该应用程序时,它会抛出此错误:
Undefined is not an object (evaluating '_this3.state.hearts[i].right')
还有一个警告:
Warning: setState(...): Cannot update during an existing state transition
部分代码如下所示。如果我删除行onComplete={this.removeHeart(v.id)}
,则不会出现错误或警告。但这只是因为我们没有正确地摧毁心脏对象。有人能指出我做错了吗?
class App extends Component {
constructor(props) {
super(props);
this.state = {hearts: []}
this.addHeart = this.addHeart.bind(this);
this.removeHeart = this.removeHeart.bind(this);
}
addHeart() {
startCount += 1;
this.state.hearts.push({
id: startCount,
right: getRandomNumber(50, 150)
});
this.setState(this.state);
}
removeHeart(v) {
var index = this.state.hearts.findIndex((heart) => heart.id === v);
this.state.hearts.splice(index, 1);
this.setState(this.state);
}
render() {
return (
<View style={styles.container}>
<TouchableWithoutFeedback style={styles.container} onPress={this.addHeart}>
<View style={styles.container}>
{
this.state.hearts.map((v, i) =>
<AnimatedHeart
key={v.id}
onComplete={this.removeHeart(v.id)}
style={{right: this.state.hearts[i].right}}
/>
, this)
}
</View>
</TouchableWithoutFeedback>
<Text style={styles.message}>Tap anywhere to see hearts!</Text>
</View>
);
}
}
答案 0 :(得分:2)
您正以错误的方式将参数传递给removeHeart
<View style={styles.container}>
{
this.state.hearts.map((v, i) =>
<AnimatedHeart
key={v.id}
onComplete={this.removeHeart.bind(this,v.id)}
style={{right: this.state.hearts[i].right}}
/>)
}
</View>
使用箭头函数表示法时无需将this
传递给地图
答案 1 :(得分:2)
您实际上正在使用当前代码调用该函数。您需要为触发器提供函数引用,而不是实际调用该函数。意
onComplete={this.removeHeart(v.id)}
应该是这个
onComplete={() => this.removeHeart(v.id)}
当渲染周期关闭时,它调用removeHeart函数,该函数在渲染发生时最终调用setState cannot set state in a transition