使用多个值来反应本机setState

时间:2016-10-12 01:46:27

标签: javascript reactjs react-native ecmascript-6 setstate

我在构造函数中定义了我的状态。

// friendlyFire service - service that interacts with firebase


// showHomeFeed - called when user visits home route

showHomeFeed()( {
    ... update current feed 
    ... return a promise with posts data for feed & lastEntryId
}

subscribeToHomeFeed(latestEntryId) {
    console.log('subscribeToHomeFeed was this called');
    return this._subscribeToFeed(`/feed/${this.user.uid}`, latestEntryId, true);
}




// _subscribeToFeed: General feed subscription method to be used with wrapper methods like subscribeToHomeFeed

_subscribeToFeed(uri, latestEntryId = null, fetchPostDetails = false) {
    console.log('_subscribeToFeed was this called');
    var deferred = this.$q.defer();
    let feedRef = this.database.ref(uri);

    if (latestEntryId) {
        // Set up ref to only posts from last item posted and after
        feedRef = feedRef.orderByKey().startAt(latestEntryId);
    }

    feedRef.on('child_added', feedData => {

        console.log('feed  subscription child added called');

        // Update, but don't include posts after last item posted
        if (feedData.key !== latestEntryId) {
            console.log('feed subscription child added called inside if');

            // Get the postDetails using the feedData.key form posts uri where all posts details are stored


            this.database.ref(`/posts/${feedData.key}`).once('value').then((results) => {

                // NOTE: This is logging in the console with info even after 1st upload(new post/child added)
                console.log(results, 'results inside subscribe to homefeed');


                // Store in the  promise
                deferred.resolve(results);
            });
        }
    });

    // store ref in order for later clean up and end listeners when not in use 
    this.firebaseRefs.push(feedRef);

    // Return the promise to be used in the contoller 
    return deferred.promise;
}

然后在另一个函数中,我试图仅为order.brand

设置state
  constructor(props) {
    super(props);
    this.state = {
    order: props.data ? { ...props.data } : { title: '', birthdate: '' , gender: '', startdate: '', starttime: '', brand: null},

注释行覆盖所有元素,第二行返回未定义的顺序。

保存只有一个具有多个值的状态项的正确语法是什么。

2 个答案:

答案 0 :(得分:1)

如评论中所述,您可以使用{"result":[{"id":2,"name":A"},{"id","pop"},...]} 修改对象值:

update

请参阅https://facebook.github.io/react/docs/update.html

答案 1 :(得分:0)

只是要注意为什么存在该错误,在您使用它的地方,订单实际上可能是未定义的。

您喜欢尝试使用{...this.state.order}