reactjs - 反应原生: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
根本不更新。_loadMoreAsync
startDate
道具company
更改后,我希望得到以下输出:
将 myCompany 设置为 companyName
使用公司公司名称
但相反,我得到:
将 myCompany 设置为 companyName
没有选择公司!
我试图减少代码以将其剥离到最重要的部分。对此有何建议?
解决方案
Google for useEffect 陈旧关闭。
当从 useEffect 调用该函数时,它是从一个陈旧的上下文中调用的——这显然是一个 javascript 功能:) 所以基本上你遇到的行为是预期的,你需要找到一种解决方法。
一种方法可能是将(可选)参数添加到您从 useEffect 传递的 _loadMoreAsync。如果此参数未定义(从其他地方调用时将被定义),则使用 state 中的值。
推荐阅读
- c++ - 用 Linux 编译的 C++ windows 可执行文件需要额外的 DLL
- java - 如何实现特定的类型转换器?
- reactjs - Redux Form 没有触发提交功能
- python - 无法在 Heroku 上运行 Flask Socket.io chatapp:进程以状态 4 退出
- python - 按字符串反向排序列表
- python - 按钮未显示在窗口中
- java - 第二个 JPanel 和 JTexField 看起来太局促了
- java - 一个程序中的多个 Elasticsearch 连接
- python - 如何处理 docker 容器中的 403 禁止错误?
- testing - JMeter如何连续运行两个并行线程集