从FlatList了解React Natives setState和componentWillMount

时间:2019-03-08 12:55:42

标签: reactjs react-native expo

因此,我尝试使用expo和expo audio制作一个简单的应用程序,该应用程序将生成音频按钮和文本的列表。但是我无法弄清楚在重绘setState OUTSIDE componentWillMount时反应如何工作,以及如何使用新的URI重新制作声音对象

所以现在它可以工作,但是只能播放FIRST URI,我认为这是因为对象仍然存在。

它不会更改按钮的状态,我知道这是因为react出于某种原因无法从FlatList看到它的更改

如果我仅在渲染视图中创建一个按钮,它将在其外部运行。

如果我使用LegacyImplementation = true,则FlatList将呈现setStates。但是我警告说,这已被弃用。并同时为所有按钮呈现

这是我的handlerClass:

export class TSSGetter extends React.Component {

  constructor(props){
    super(props);
    this.state ={ 
      isLoading: true,
      playingStatus: "Play"
    }
  }



  retrieveData() {
    const endpoint = 'http://127.0.0.1:3333/get'

    const data = {
        "userId": "123412341234",
        "hmac": "detteerikkeenrigtighmac"
    }
    return new Promise((resolve, reject) => {
        fetch(endpoint, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'content-type':'application/json'
            },
            body: JSON.stringify(data)
        })
        .then((resp) => {
          console.log('hej return')
            return resp.json();

        })
        .then((resp) => {
            resolve(resp);
            console.log('resp')
        }).catch(function(error) {
          console.log(error,'naeh')
        });
    });
}

  componentDidMount(){


     this.retrieveData()
     .then((resp) => {
        var pages = resp.books.contentObjects

        pages.map((userData) => {
          console.log('superduper pages', userData.contentObjectId)

        })
        this.setState({
            isLoading: false,
            dataSource: resp.books.contentObjects,
            dataroot: resp.books

        });

    }).catch((err) => {
        //handle error

        console.log("Api call error2");
     alert(err);
    })
  }

  async _playRecording(AudioURL) {
    console.log(AudioURL)
    const { sound } = await Audio.Sound.createAsync(
      {uri: AudioURL},
      {
        shouldPlay: true,
        isLooping: true,
      },
      this._updateScreenForSoundStatus,
    );
    this.sound = sound;
    this.setState({
      playingStatus: 'playing'
    });
  }

  _updateScreenForSoundStatus = (status) => {
    if (status.isPlaying && this.state.playingStatus !== "playing") {
      this.setState({ playingStatus: "playing" });
    } else if (!status.isPlaying && this.state.playingStatus === "playing") {
      this.setState({ playingStatus: "donepause" });
    }
  };

  async _pauseAndPlayRecording() {
    if (this.sound != null) {
      if (this.state.playingStatus == 'playing') {
        console.log('pausing...');
        await this.sound.pauseAsync();
        console.log('paused!');
        this.setState({
          playingStatus: 'donepause',
        });
      } else {
        console.log('playing...');
        await this.sound.playAsync();
        console.log('playing!');
        this.setState({
          playingStatus: 'playing',
        });
      }
    }
  }

  _syncPauseAndPlayRecording() {
    if (this.sound != null) {
      if (this.state.playingStatus == 'playing') {
        this.sound.pauseAsync();
      } else {
        this.sound.playAsync();
      }
    }
  }

  _playAndPause = (AudioURL) => {
    console.log(AudioURL)
    switch (this.state.playingStatus) {
      case 'Play':
        this._playRecording(AudioURL);
        break;
      case 'donepause':
      case 'playing':
        this._pauseAndPlayRecording();
        break;
    }
  }

  render(){

    if(this.state.isLoading){
      return(
        <View style={{flex: 1, padding: 20}}>
          <ActivityIndicator/>
        </View>
      )
    }
    const styling = {
      flex: 1, 
      paddingTop:10
      // flexDirection: 'row'
    }
    const data = this.state.dataroot;
    return(

      <View style={styles.container}>

        <FlatList

          data={this.state.dataSource}

          renderItem={({item}) => 
          <View>

          <TouchableOpacity style={styles.button} onPress={() => this._playAndPause(item.AudioURL)}>
          <Text style={styles.buttonText}>
                {this.state.playingStatus}+ {item.contentObjectId}
              </Text>
            </TouchableOpacity>
          <Text style={styles.description}>
          {item.text}, 

          </Text>
          </View>

          }
         keyExtractor={(item, index) => item.contentObjectId}

        />
      </View>
    );

  }
}

更新:在平面列表中设置extraData = {this.state}会更新按钮。但是所有按钮。如何更改按钮的范围?

2 个答案:

答案 0 :(得分:1)

您可以为FlatList中的项目创建特定的组件。每个项目将具有各自的状态。

import React, { Component } from "react";
import { StyleSheet, Text, View } from "react-native";
import { FlatList } from "react-native-gesture-handler";

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <FlatList
          keyExtractor={(item, index) => index.toString()}
          data={[1, 2, 3, 4, 5]}
          renderItem={({ item }) => <Sound />}
        />
      </View>
    );
  }
}

class Sound extends Component {
  constructor() {
    super();
    this.state = {
      status: "IDLE"
    };
  }

  onChangeState = value => {
    this.setState({
      status: value
    });
  };

  render() {
    const { status } = this.state;

    return (
      <View style={{width: 200,paddingVertical: 10}}>
        <Text>Status: {status}</Text>
        <View style={{ flex: 1,flexDirection: "row", justifyContent: "space-between" }}>
          <Text onPress={() => this.onChangeState("PLAYING")}>PLAY</Text>
          <Text onPress={() => this.onChangeState("STOPPED")}>STOP</Text>
          <Text onPress={() => this.onChangeState("PAUSED")}>PAUSE</Text>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 100,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  }
});

sound

答案 1 :(得分:0)

我在文档here中签出,发现只要您通过状态道具,它就会重新呈现,请参见以下说明:

  

通过将extraData = {this.state}传递给FlatList,我们确保当state.selected更改时FlatList本身将重新呈现。如果不设置此道具,FlatList将不知道它需要重新渲染任何项目,因为它也是PureComponent,并且道具比较不会显示任何更改。