我正在使用 React、Redux 和 Firebase 创建一个电影搜索应用。我创建了一个函数(isPresentMovie)来验证电影是否已在 Facebook 中,我的期望是根据验证结果返回“添加电影”/“删除电影”按钮。
import React, { Component } from 'react'
import { connect } from 'react-redux';
import { addFav, removeFav, getDetail } from '../../store/actions/getDetailAction'
import { firestoreConnect } from 'react-redux-firebase';
import { compose } from 'redux'
const button = {
marginLeft:'10px',
marginRight:'10px',
}
export class Favorite extends Component {
handleRemove = (e) => {
e.preventDefault();
this.props.removeFav()
};
handleAdd = (e) => {
e.preventDefault();
this.props.addFav()
}
isPresentMovie = () => {
const validation = this.props.favorites.filter(favorite => favorite.authorId == this.props.auth.uid).find(favorite => favorite.imdbID == this.props.movie.imdbID);
if(validation == undefined){
return (<button type="submit" className="btn btn-danger btn-bg mt-1" onClick={this.handleRemove} style={button}>Remove From Favorite</button>);
} else {
return (<button type="submit" className="btn btn-primary btn-bg mt-1" onClick={this.handleAdd} style={button}>Add To Favorite</button>);
}
}
render() {
return (
<div className="d-flex">
{this.isPresentMovie()}
</div>
)
}
}
const mapStateToProps = state => ({
favorites: state.firestore.ordered.favorites,
auth: state.firebase.auth,
movie: state.movie.movie,
})
export default compose(
connect(mapStateToProps,{ addFav, removeFav, getDetail }),
firestoreConnect([
{ collection: 'favorites' }
])
)(Favorite);
问题 1:虽然我使用箭头函数,但该函数并未在 render() 中调用。错误提示“TypeError: Cannot read property 'filter' of undefined” 尝试使用 .bind(this),结果相同.
问题2:我最初怀疑它没有正确渲染,但是如果我没有在函数内部使用任何方法,它就会正确显示。
如果是方法的问题,是否有其他方法可以根据 API 数据验证 Fb 中的数据?或者通过另一种方式,我可以根据我创建的函数验证数据?
最佳答案
favorites
属性未定义,可能是因为初始加载时数据正在处理来自 firebase 的数据。您将遇到的另一个问题是您的按钮需要具有 key
属性。虽然 favorites 未定义,您可以从 isPresent 渲染 null,试试这个:
isPresentMovie = () => {
if (!Array.isArray(this.props.favorites)) {
return null;
}
const validation = this.props.favorites.filter(favorite => favorite.authorId == this.props.auth.uid).find(favorite => favorite.imdbID == this.props.movie.imdbID);
if(validation == undefined){
return (<button key="no-validation" type="submit" className="btn btn-danger btn-bg mt-1" onClick={this.handleRemove} style={button}>Remove From Favorite</button>);
} else {
return (<button key="validation" type="submit" className="btn btn-primary btn-bg mt-1" onClick={this.handleAdd} style={button}>Add To Favorite</button>);
}
}
关于javascript - React 函数没有在 render() 中被回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61212428/