Sungpah Lee
Sungpah Lee

Reputation: 1021

Array State update in React-native

I'm trying to update a specific element of array state in React-native. As an example, I created 3 Modals with its initial visibility as false.

Here I want to independently control 3 Modals with each button on the corresponding Modal page. So I set the initial state variable "modalVisible" as an array with 3 length. Then, tried to update one element of modalVisible with this kind of command => this.setState({modalVisible[2]: true}), which ends up not working with this error(Syntax Error: ... Unexpected token). If this is not possible, then I have to find the way of doing this equivalently. For instance in the for loop, I need to write like this : {this.state.modalVisible_{i}} so that the code can programmably know where to locate.

The below is my current code.

 constructor(props) {
    super(props);
    this.state = {
      modalVisible: [false,false,false]
    };
  }


  setModalVisible(visible,th) {
    this.setState({modalVisible[th]: visible});
  }


  _render_modal(){
    var rows = [];
    for (var i=0; i < 2; i++) {
      rows.push(
      <View>
        <TouchableHighlight onPress={() => {
          this.setModalVisible(true,i)
          }}>
          <Text>Show Modal {i} th..</Text>
        </TouchableHighlight>

        <Modal
          animationType={"slide"}
          transparent={false}
          visible={this.state.modalVisible[i]}
          onRequestClose={() => {alert("Modal has been closed.")}}
          >
         <View style={{marginTop: 22}}>
          <View>
            <Text>Hello World!</Text>

            <TouchableHighlight onPress={() => {
              this.setModalVisible(!this.state.modalVisible[i],i)
            }}>
              <Text>Hide Modal</Text>
            </TouchableHighlight>

          </View>
         </View>
        </Modal>

      </View>

      );
    } 

    return(
       <View>{rows}</View>
      );
  }


render() {
    var spinner = this.state.isLoading ?
    ( <ActivityIndicator
          size='large'/> ) :
    ( <View/>);
    //이런건 렌더링 되자마자. 
    //dynamically modal 을 만들 수가 있나?

    return (

      <View style={styles.container}>
        {this._render_modal()}
      </View>
    );
}

Upvotes: 1

Views: 3713

Answers (1)

nabn
nabn

Reputation: 2408

You can't directly modify an array index in a setState call.

You have to first modify the array and then pass it to setState.

setModalVisible(visible, th) {
  let modalVisible = this.state.modalVisible
  modalVisible[th] = visible
  this.setState({ modalVisible: modalVisible })
  // shorthand: this.setState({modalVisible})
}

To do it in an immutable way, you'd do something like this:

setModalVisible(visible, th) {
  const previousState = this.state.modalVisible
  this.setState({
    modalVisible: [
      ...previousState(0, th),
      visible, 
      ...previousState(th+1, previousState.length+1)
    ]
  })
}

Upvotes: 4

Related Questions