React Native 筛选数据时无法首次提取数据

ygya80vv  于 2022-11-25  发布在  React
关注(0)|答案(1)|浏览(142)

我尝试通过类似http://localhost/api/offer/get-offerlist?id=${userId}的方式获取数据,userId从react原生AsyncStorage获取。
这是对我请求的回应

[
{
    "_id": "6369553f0617161cf0e7c991",
    "location": {
        "coordinates": [
            -0.127585,
            51.5072167
        ],
        "type": "Point"
    },
    "option": {
        "enum": [
            "Charging Station"
        ],
        "type": "Point"
    },
    "userId": "635696833ab4103a08f96713",
    "name": "ISLAMABAD",
    "buildingName": "Habib Bank Plaza",
    "rate": 0.5,
    "longitude": "-0.127585",
    "latitude": "51.5072167",
    "locationShortDescription": "Habib Bank Plaza building near II Chandigar Road",
    "__v": 0,
    "result": [
        {
            "_id": "636bb6104395231b5c212bab",
            "request": {
                "enum": [
                    {
                        "enum": [
                            0
                        ]
                    }
                ]
            },
            "offerUserId": "635696833ab4103a08f96713",
            "stationId": "6369553f0617161cf0e7c991",
            "rate": 0.2,
            "__v": 0
        },
        {
            "_id": "636bcc5c0f20bf1484c92be0",
            "request": {
                "enum": [
                    {
                        "enum": [
                            0
                        ]
                    }
                ]
            },
            "adUserId": "635696833ab4103a08f96713",
            "offerUserId": "635696833ab4103a08f96713",
            "stationId": "6369553f0617161cf0e7c991",
            "rate": 1.6,
            "__v": 0
        }

)的名称。
我尝试使用过滤器和一些方法将filed _id与result[stationId]匹配,但问题是,数据不是第一次过滤,但当刷新屏幕时,所有数据都成功提取。

代码:

const [userId, setUserID] = useState("");
  const [list, setList] = useState("");
  const [loading, setLoading] = useState(false);
  const [getStationsId, setGetStationsId] = useState("");

  const [filterRecord, setFilterRecord] = useState("");

  const getOfferList = async () => {
    try {
      setLoading(true);
      const userId = await AsyncStorage.getItem('userId');
      const response = await fetch(
        `http://localhost/api/offer/get-offerlist?id=${userId}`,
        {
          headers: {
            accept: 'application/json',
            'Content-Type': 'application/json'    
          },
        },
      );
      const data = await response.json();

        //StationID from result Object
      const extractedStationId = data.map((item) => item.result);
      setGetStationsId(extractedStationId);

      const myArrayFiltered = data.filter((el,index) => {
      return getStationsId[index].some(f => {
        return f.offerUserId === el.userId;
      });
    });
      setLoading(false);
      setList(data);
      setFilterRecord(myArrayFiltered);
    } catch (e) {
      console.log(e);
      setLoading(false);
    }
  };

 useEffect(() => {  
    getOfferList();
  }, []);

屏幕代码:

const Item = ({
    name,
    buildingName,
    locationShortDescription,
    latitude,
    longitude,
    rate,
    userRate,
    createdAt,
  }) => (
    <View>
      <View className="flex flex-row justify-between pb-4 pl-3 pr-3 py-2  border-t-4 border-green-700">
        <View className="flex flex-row">
          <Image
            source={require('../../assets/images/avatar.png')}
            className="w-16 h-14"></Image>
          <Text className="text-slate-600 font-semibold">
            {name}
            {'\n'}
            {buildingName}
            {'\n'}
            {locationShortDescription}
            {'\n'}
            {latitude}
            {'\n'}
            {longitude}
            {'\n'}
            {rate}
            {'\n'}
            {userRate}
            {'\n'}
            {createdAt}
            {'\n'}
            <View className="flex flex-row">
              <MaterialCommunityIcons
                name="leaf-circle-outline"
                size={25}
                color={'#2ea44f'}
                style={{marginTop: 12}}
              />
              <MaterialCommunityIcons
                name="leaf-circle-outline"
                size={25}
                color={'#2ea44f'}
                style={{marginTop: 12}}
              />
            </View>
            {'\n'}
            <View className="flex flex-row">
              <FontAwesome name="star" size={25} color="#f1c833" />
              <Text className="text-lg  text-black ml-1">4,9</Text>
              <Text className="text-lg  text-gray-400"> (302)</Text>
            </View>
          </Text>
        </View>
      </View>
    </View>
  );
  const renderItem = ({item}) => (
    <Item
      name={item.name}
      buildingName={item.buildingName}
      locationShortDescription={item.locationShortDescription}
      latitude={item.latitude}
      longitude={item.longitude}
      rate={item.rate}
      userRate={item.result[0].rate}
      createdAt={item.result[0].createdAt}
    />
  );
  return (
    <>
      {loading && <Loader />}
      {filterRecord && (
        <SafeAreaView>
          <View className="flex flex-col p-2">
            <View className="my-4 bg-white rounded drop-shadow-2xl">
              <FlatList
                data={filterRecord}
                renderItem={renderItem}
                keyExtractor={item => item._id}
              />
            </View>
          </View>
        </SafeAreaView>
      )}
    </>
  );
}

我希望我能够第一次使用从移动的本地存储获得的用户ID获取数据。

2guxujil

2guxujil1#

使用UseLayoutEffect而不是useEffect,然后添加if loading = true以返回正在加载的文本,如果没有加载,则返回主要内容。

相关问题