简体   繁体   English

用于反应钩子的 useEffect 的替代品

[英]alternative of useEffect for react hooks

First, I run a graphql query and then use its results to render some items using the FlatList .首先,我运行 graphql 查询,然后使用其结果使用FlatList呈现一些项目。 This works fine.这工作正常。

On another screen, I run another mutation using apollos refetch option, such that whenever that mutation is successful, the first query will refetch data where ever it is used.在另一个屏幕上,我使用 apollos refetch选项运行另一个突变,这样每当突变成功时,第一个查询将在使用它的地方重新获取数据。 The refetching part works fine and I have tested it on other screens.重新获取部分工作正常,我已经在其他屏幕上对其进行了测试。 So automatically, the data in WhiteList is updated .因此, WhiteList中的data会自动更新

However the friendList is not updated so the FlatList doesn't get updated .但是, friendList没有更新,因此FlatList 没有得到更新

How can I fix this?我怎样才能解决这个问题? useEffect could have been an option but using the custom graphql hook inside it gives me invalid hook call error. useEffect可能是一个选项,但在它内部使用自定义 graphql 钩子会给我invalid hook call错误。 What else can I do?我还可以做些什么?

export const WhitelistBar: React.FC = () => {
  const [friendList, setFriendList] = useState<Friend[]>();
  const [originatorId, setOriginatorId] = useState<number>();

  useEffect(() => {
    //console.log('friendlist', friendList);
  }, [useGetMyProfileQuery]);
  
  const _onCompleted = (data) => {
    console.log('running', data);
    let DATA = data.me.friends.nodes.map(
      (item: {
        id: number;
        firstName: string;
        rating: number;
        vehicles: Vehicle[];
        friends: UserConnection;
      }) => ({
        id: item.id,
        imageUrl: defaultUrl,
        name: item.firstName,
        rating: item.rating,
        vehicles: item.vehicles,
        numberOfFriends: item.friends.totalCount,      
      }),
    );
    setFriendList(DATA);
    console.log('daattaaa', DATA);
    setOriginatorId(data.me.id)
  };

  const _onError = () => {
    let DATA = [
      {
        id: 1,
        imageUrl: defaultUrl,
        name: 'Friend',
      },
      {
        id: 2,
        imageUrl: defaultUrl,
        name: 'Friend',
      },
      {
        id: 3,
        imageUrl: defaultUrl,
        name: 'Friend',
      },
    ];
    setFriendList(DATA);
    setOriginatorId(0);
  };

  const { data } = useGetMyProfileQuery({
    onCompleted: _onCompleted,
    onError: _onError,
  });

  return (
    <View style={scaledStyles.container}>
      <View style={scaledStyles.whiteListBarTitle}>
        <Text style={scaledStyles.whiteListBarText}>Meine Freunde</Text>
      </View>
      <View style={{ flexDirection: 'row' }}>
        <FlatList
          showsHorizontalScrollIndicator={false}
          data={friendList}
          horizontal={true}
          renderItem={({ item }) => (
            <WhitelistItem
              title={item.name}
              face={item.imageUrl}
              numberOfFriends={item.numberOfFriends}
              vehicles={item.vehicles}
            />
          )}
          keyExtractor={(item) => item.id.toString()}
        />
      </View>
    </View>
  );
};

Edit:编辑:

I also tried this but this renders nothing for now:我也试过这个,但现在什么都没有:

 const showFlatList = (friendList: Friend[] | undefined) => {
    return (
      <FlatList
        showsHorizontalScrollIndicator={false}
        data={friendList}
        horizontal={true}
        scrollEnabled
        renderItem={({ item }) => (
          <WhitelistItem
            title={item.name}
            face={item.imageUrl}
            firstName={item.name}
            rating={item.rating}
            numberOfFriends={item.numberOfFriends}
            vehicles={item.vehicles}
            originatorId={originatorId}
          />
        )}
        keyExtractor={(item) => item.id.toString()}
      />
    );
  };
  useEffect(() => {
    showFlatList(friendList);
  }, [useGetMyProfileQuery]);

and this in the main return instead of the FlatList:这在主返回而不是 FlatList 中:

 {data && showFlatList}

Also, tried this but Argument of type '(DATA: any) => void' is not assignable to parameter of type 'EffectCallback'.ts(2345)此外,尝试了这个,但Argument of type '(DATA: any) => void' is not assignable to parameter of type 'EffectCallback'.ts(2345)

     useEffect((DATA: any) => {
        setFriendList(DATA)
      }, [DATA])

You can't use hook as effect dependency - only variables/props/values.您不能将钩子用作效果依赖项 - 只能使用变量/道具/值。

You can use hook inside effect function (body).您可以使用挂钩内部效果 function(主体)。

If it is a component dependent on other (parent's) data/values - pass them as prop and use in effect dependency.如果它是依赖于其他(父级)数据/值的组件 - 将它们作为 prop 传递并在效果依赖项中使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM