开发者问题收集

如何在 React-Native 中通过 fetch() 从函数返回数据

2020-01-23
107

我为我的帖子创建了一个 FlastList,在其中调用一个函数来返回帖子的点赞,但它给出了一个错误:

[Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}). If you meant to render a collection of children, use an array instead.
    in RCTView (at Testing.js:196)
    in TouchableWithoutFeedback (at Testing.js:185)
    in RCTView (at Testing.js:184)
    in RCTView (at Testing.js:165)
    in TouchableWithoutFeedback (at Testing.js:160)
    in RCTView (at VirtualizedList.js:1925)
    in CellRenderer (at VirtualizedList.js:767)
    in RCTView (at ScrollView.js:1038)
    in RCTScrollView (at ScrollView.js:1178)
    in ScrollView (at VirtualizedList.js:1183)
    in VirtualizedList (at FlatList.js:676)
    in FlatList (at Testing.js:151)
    in RCTView (at Testing.js:147)
    in Testing
    in SceneView (at StackView.tsx:269)
    in RCTView (at CardContainer.tsx:171)
    in RCTView (at CardContainer.tsx:170)
    in RCTView (at Card.tsx:455)
    in RCTView (at createAnimatedComponent.js:151)
    in AnimatedComponent (at Card.tsx:442)
    in PanGestureHandler (at Card.tsx:435)
    in RCTView (at createAnimatedComponent.js:151)
    in AnimatedComponent (at Card.tsx:431)
    in RCTView (at Card.tsx:424)
    in Card (at CardContainer.tsx:138)
    in CardContainer (at CardStack.tsx:503)
    in RCTView (at CardStack.tsx:110)
    in MaybeScreen (at CardStack.tsx:496)
    in RCTView (at CardStack.tsx:93)
    in MaybeScreenContainer (at CardStack.tsx:403)
    in CardStack (at StackView.tsx:384)
    in KeyboardManager (at StackView.tsx:382)
    in RNCSafeAreaView (at src/index.tsx:26)
    in SafeAreaProvider (at SafeAreaProviderCompat.tsx:34)
    in SafeAreaProviderCompat (at StackView.tsx:379)
    in StackView (at StackView.tsx:41)
    in StackView (at createStackNavigator.tsx:33)
    in Unknown (at createNavigator.js:80)
    in Navigator (at createAppContainer.js:430)
    in NavigationContainer (at renderApplication.js:40)
    in RCTView (at AppContainer.js:101)
    in RCTView (at AppContainer.js:119)
    in AppContainer (at renderApplication.js:39)]

fetch() 工作正常,我得到了点赞,但是当我返回数据时,出现了那个错误。 我不明白为什么我会收到这个错误,以及它将如何删除,以及我将如何在我的应用程序上获得点赞的帖子。

这是我的代码。

likes = async item => {
    const response = await fetch(
      'http://192.168.0.3:1234/post_likes?post_id=' + item.id,
    );
    const data = await response.json();
    let likes = data[0].likes;
    console.log(likes);
    return <Text>{likes}</Text>;
  };

  render() {
    return (
      <View style={styles.container}>
        <HeaderIcon />
        {this.state.loading && <ActivityIndicator size="large" color="cyan" />}

        <FlatList
          onScroll={({nativeEvent}) => {
            if (this.isCloseToBottom(nativeEvent)) {
              this.getMorePost();
            }
          }}
          data={this.state.post}
          keyExtractor={(item, index) => index.toString()}
          renderItem={({item}) => (
            <TouchableWithoutFeedback
              style={styles.main}
              onPress={() => {
                this.openPost(item);
              }}>
              <View style={styles.main}>
                <View style={styles.row}>
                  {/* <View>{this.img(item)}</View> */}
                  <View>
                    <Image
                      style={styles.profilePic}
                      source={{uri: item.featuredImage}}
                    />
                  </View>

                  <View>
                    <Text style={styles.title}>{item.post_title}</Text>
                  </View>
                </View>
                <Image
                  // resizeMode="stretch"
                  style={styles.image}
                  source={{uri: item.featuredImage}}
                />
                <View>
                  <TouchableWithoutFeedback
                    onPress={() => {
                      Share.share({
                        title: item.post_title,
                        message:
                          item.section_seo_url +
                          item.post_content.replace(/<[^>]*>|&nbsp;/g, ' ') +
                          item.featuredImage,
                        url: item.featuredImage,
                      });
                    }}>
                    <View
                      style={{
                        justifyContent: 'center',
                        padding: 10,
                        flexDirection: 'row',
                      }}>
                      <Image
                        source={require('../image/wlogo.png')}
                        style={{height: 40, width: 40, paddingLeft: 50}}
                      />
                      {this.likes(item)}
                    </View>
                  </TouchableWithoutFeedback>
                </View>
              </View>
            </TouchableWithoutFeedback>
          )}
        />
      </View>
    );
  }
}
1个回答

按照我的说法,您正在进行多个 api 调用

Instead of that you can get your posts data with your likes from backend in simple 
one api call.

You just need to add join query with your likes table in your get-posts request 
which will return all your post with likes 

So, you will get your all post with likes in one api call instead of these much 
of calls.

Which is good practise for us.it will increase your app performance as well as
less api calls so it is good for server as well 

解决方案如下

 add one more field likes to your post table 

 what you can do is when user like/dislike your post then get your likes
 from post table and increment by one else decrement by one as per user 
 like/dislike and update back to post table.
Prakash Karena
2020-01-23