猿问

当屏幕获得焦点时如何重新渲染 react-native FlatList?

我正在开发一个带有 react-navigation 的 react-native 应用程序。

用户打开应用程序时看到的第一个屏幕有一个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”作为名称


临摹微笑
浏览 174回答 2
2回答

慕码人2483693

将此代码放在您的构造函数中。我希望它会帮助您。this.props.navigation.addListener(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'didFocus',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;payload => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// call method which you want to call&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// call those method where your state is update&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;});&nbsp; &nbsp; &nbsp;}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答