首页 > 解决方案 > 反应原生:useState 没有正确更新

问题描述

我是本机反应的新手,目前正在与无限滚动列表视图作斗争。这是一个日历列表,需要根据所选公司进行更改(作为道具给出)。问题是:道具(以及myCompany状态也发生了变化,但在_loadMoreAsync方法prop.company中都myCompany保持了它们的初始值。

import * as React from 'react';
import { FlatList } from 'react-native';
import * as Api from '../api/api';
import InfiniteScrollView from 'react-native-infinite-scroll-view';

function CalenderFlatList(props: { company: any }) {
  const [myCompany, setMyCompany] = React.useState(null);
  const [data, setData] = React.useState([]);
  const [canLoadMore, setCanLoadMore] = React.useState(true);
  const [startDate, setStartDate] = React.useState(undefined);

  let loading = false;

  React.useEffect(() => {
    setMyCompany(props.company);
  }, [props.company]);

  React.useEffect(() => {
    console.log('set myCompany to ' + (myCompany ? myCompany.name : 'undefined'));
    _loadMoreAsync();
  }, [myCompany]);

  async function _loadMoreAsync() {
    if ( loading )
      return;

    loading = true;

    if ( myCompany == null ) {
      console.log('no company selected!');
      return;
    } else {
      console.log('use company: ' + myCompany.name);
    }

    Api.fetchCalendar(myCompany, startDate).then((result: any) => {
      // code is a little more complex here to keep the already fetched entries in the list...
      setData(result);

      // to above code also calculates the last day +1 for the next call
      setStartDate(lastDayPlusOne);

      loading = false;
    });
  }

  const renderItem = ({ item }) => {
    // code to render the item
  }

  return (
    <FlatList
      data={data}
      renderScrollComponent={props => <InfiniteScrollView {...props} />}
      renderItem={renderItem}
      keyExtractor={(item: any) => '' + item.uid }
      canLoadMore={canLoadMore}
      onLoadMoreAsync={() => _loadMoreAsync() }
    />
  );
}

我在这里不明白的是为什么在正确更新并完全加载日历的下一个条目时myCompany根本不更新。_loadMoreAsyncstartDate

道具company更改后,我希望得到以下输出:

将 myCompany 设置为 companyName

使用公司公司名称

但相反,我得到:

将 myCompany 设置为 companyName

没有选择公司!

我试图减少代码以将其剥离到最重要的部分。对此有何建议?

标签: reactjsreact-nativeuse-effectuse-state

解决方案


Google for useEffect 陈旧关闭。

当从 useEffect 调用该函数时,它是从一个陈旧的上下文中调用的——这显然是一个 javascript 功能:) 所以基本上你遇到的行为是预期的,你需要找到一种解决方法。

一种方法可能是将(可选)参数添加到您从 useEffect 传递的 _loadMoreAsync。如果此参数未定义(从其他地方调用时将被定义),则使用 state 中的值。


推荐阅读