Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

state with 2 dimentional array

I want to have a 2 dimensional array for the state. Once a user clicks on a touch area. It will update a value in this 2 dimensional array. For some reason, I got error with my code. The following are the constructor and the onPress function

export default class App extends Component<Props> {
    constructor(Props){
      super(Props);
      this.state = {
        test: 'U',
        array: [
          ['n','n','n'],
          ['6','n','n'],
          ['n','n','n'],
        ]
      };
    }

    onPress = (row,colum) => {
      this.setState({
        array[row][colum]: this.test
      });
    }

    render() {
      return (
          <View style={styles.middleWrapper}>
            <TouchableOpacity style={[styles.child]} onPress={this.onPress(1,0)}><Text>  {this.state.array[1][0]}</Text></TouchableOpacity>
          </View>
      );
    }
}

It seems the onPress method is not right. But I do not know what is not right. Please help. Thanks.

**

Update 1:

**

get the error:

\node_modules\react-native\scripts\App.js: Unexpected token, expected "," (38:11)

  36 |   onPress = (row, column) => () => {
  37 |     this.setState({
> 38 |       array[row][colum]: this.test
     |            ^
  39 |     })
  40 |   }
  41 |
like image 576
Denvi Avatar asked Jan 27 '23 02:01

Denvi


1 Answers

The Unexpected token syntax error is from the object in your setState call. The key needs to be wrapped in another set of square brackets:

this.setState({
    [array[row][column]]: this.test 
  })

This doesn't solve the problem, though.

// Create a copy of the state array so that you don't mutate state.
const array = [...this.state.array];

// Update the copy with the new value.
array[row][column] = this.test;

// Replace the state array with the new copy.
this.setState({ array });
like image 124
Dov Rine Avatar answered Feb 08 '23 05:02

Dov Rine