反应:无法在componentWillMount

时间:2018-11-05 22:55:38

标签: react-native

我是react-native的业余爱好者,我似乎无法理解我的代码在下面发生的事情:我可以在控制台上将Promise中的“数据”记录为问题,但是当我尝试时使用this.setState将状态设置为“ liked”和“ likedBack”,似乎它们与初始状态并没有真正的变化。在componentWillMount()内部调用此函数。对我在这里做错的任何想法吗?任何提示都会有很大帮助。

getMatchesUid= (uid, idPet)=>{
    Ofirebase.database().ref('relationships').child(uid).child('pets').child(idPet).on('value', snap=>{
        const relations = snap.val()
        const allMatchesUid = this.getOverlap(relations.liked,relations.likedBack)
        console.log('allMatches', allMatchesUid)
        this.stateFunction(this.state.matches, allMatchesUid) 
        const promiseliked = allMatchesUid.map(profileUid =>{
            firebase.database().ref('relationships').child(uid).child('pets').child(idPet).on('value', snap=>{
                const matches = snap.val()
                const liked = this.getValue(uid, profileUid, idPet, 'liked')
                return (liked)
            })
            const promiselikedBack = allMatchesUid.map(profileUid=>{
                const likedBack = this.getValue(uid, profileUid, idPet, 'likedBack')
                return (likedBack)
            })
            Promise.all(promiseliked).then(data => 
                this.setState({
                    liked: data,
                }))
            this.setState({
                liked: data
            }))
            Promise.all(promiselikedBack).then(data => this.setState({
                likedBack: data,
            }))

1 个答案:

答案 0 :(得分:2)

首先不要使用componentWillMount()来设置状态。 componentWillMount()在初始化(渲染)组件之前被调用,因此无法在未初始化的组件上设置状态,请使用componentDidMount()并设置状态,请查看以下链接以获取与此相关的更多信息,

https://vasanthk.gitbooks.io/react-bits/anti-patterns/04.setState-in-componentWillMount.html

相关问题