FlatList
组件,其中列出了一些产品并显示其名称。我尝试将extraData
属性添加到FlatList
组件中,但是按预期效果却不起作用。
<FlatList
data={this.state.washers}
extraData={this.state}
renderItem={this.renderItem}
keyExtractor={item => item.serialNumber}/>
state.washers
是一个对象数组,该对象的属性之一是名称。
this.state.washers: Array(2):
0: {serialNumber: "20197", model: "", name: "first washer"}
1: {serialNumber: "201908301", model: "", name: "washer 2"}
用户更改产品(洗衣机)的名称时,它会保存在名为{~productSerialNumber~}Name.txt
的文本文件中
这是侦听screen focus
事件的代码
focusListener = this.props.navigation.addListener('didFocus', async () => {
let washers = [];
if (await ReactNativeFS.exists(`${ReactNativeFS.DocumentDirectoryPath}/washers.json`)) {
washers = await ReactNativeFS.readFile(`${ReactNativeFS.DocumentDirectoryPath}/washers.json`, "ascii");
washers = JSON.parse(washers);
}
washers.forEach(async washer => {
const washerName = await ReactNativeFS.readFile(`${ReactNativeFS.DocumentDirectoryPath}/maquinas/${washer.serialNumber}Name.txt`);
washer.name = washerName;
});
this.setState({washers});
});
}
好吧,当我返回到列表屏幕时,可以看到状态已更改并已用新名称更新,但是FlatList
组件中未显示任何更改。
我所看到的是,当我单击名为“ name0”的产品(例如)并将其名称更改为“ name1”(例如),然后返回到列表屏幕,然后单击同一产品并将其名称更改为“ name2”(例如),然后FlatList
将“ name1”显示为名称
对不起,英语不好,谢谢您的帮助!! <3
答案 0 :(得分:0)
将此代码放入您的构造函数中。希望对您有所帮助。
this.props.navigation.addListener(
'didFocus',
payload => {
// call method which you want to call
// call those method where your state is update
});
}
答案 1 :(得分:0)
请查看React Navigation文档,您可以尝试使用withNavigationFocus
而不是didFocus
侦听器。
import React, { Component } from "react";
import { View } from "react-native";
import { withNavigationFocus } from "react-navigation";
class MyScreen extends Component {
componentDidMount() {
this.updateWashers();
}
componentDidUpdate(prevProps) {
// Check that screen is newly focused
if (this.props.isFocused && prevProps.isFocused !== this.props.isFocused) {
this.updateWashers();
}
}
updateWashers() {
// put in your code to read saved data
}
render() {
return <View />;
}
}
export default withNavigationFocus(MyScreen );
改编自https://reactnavigation.org/docs/en/3.x/function-after-focusing-screen.html