更新嵌套数组-ReactNative

时间:2018-11-17 15:54:56

标签: javascript reactjs react-native

我正在尝试制作本人的井字游戏。我的电路板由以下状态的数组表示:

state = {
    tablero : [
  [null, null, null], 
  [null, null, null], 
  [null, null, null]
],
}

我的板子组件是:

<View>
    <View style={styles.fila}>
      <Text style={[styles.celda, {borderTopWidth: 0, borderLeftWidth: 0}]}>
        {this.state.tablero[0][0]}
      </Text>
      <Text style={[styles.celda, {borderTopWidth: 0}]}>
        {this.state.tablero[0][1]}
      </Text>
      <Text style={[styles.celda, {borderTopWidth: 0, borderRightWidth: 0}]}>
        {this.state.tablero[0][2]}
      </Text>  
    </View>
    <View style={styles.fila}>
      <Text style={[styles.celda, {borderLeftWidth: 0}]}>
        {this.state.tablero[1][0]}
      </Text>
      <Text style={styles.celda}>
        {this.state.tablero[1][1]}
      </Text>
      <Text style={[styles.celda, {borderRightWidth: 0}]}>
        {this.state.tablero[1][2]}
      </Text>  
    </View>
    <View style={styles.fila}>
      <Text style={[styles.celda, {borderBottomWidth: 0, borderLeftWidth: 0}]}>
        {this.state.tablero[2][0]}
      </Text>
      <Text style={[styles.celda, {borderBottomWidth: 0}]}>
        {this.state.tablero[2][1]}
      </Text>
      <Text style={[styles.celda, {borderBottomWidth: 0, borderRightWidth: 0}]}>
        {this.state.tablero[2][2]}
      </Text>  
    </View>
  </View>

我想知道在印刷时如何更新我的电路板。我尝试使用传播算子,但无法弄清楚

2 个答案:

答案 0 :(得分:2)

这是您可以使用传播算子执行的操作。

state = {
    tablero : [
      [null, null, null], 
      [null, null, null], 
      [null, null, null]
    ],
}

// ---------- some code -----

function onPress({x, y}, newValue) {// press cell index
  this.setState({...state,
    tablero: Object.assign([],[...state.tablero], {
      [y]: Object.assign([], [...state.tablero[y]], {[x]: newValue})
    })
  });
}

// if we call, for example, onPress({x: 1, y: 2}, 1);
// Output state will be
// { tablero: [ [ null, null, null ], [ null, null, null ], [ null, 1, null ] ] }

顺便说一句,很棒的文章在这里:https://medium.com/@giltayar/immutably-setting-a-value-in-a-js-array-or-how-an-array-is-also-an-object-55337f4d6702

答案 1 :(得分:0)

这是一个入门的简单示例:

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  state = {
    table: [[0, 0, 0]]
  };

  toggle = (e, i) => {
    const { table } = this.state;
    table[0][i] = table[0][i] === 0 ? 1 : 0;
    console.log(table);
    this.setState({ table });
  };

  render() {
    return (
      <ul>
        {this.state.table[0].map((n, i) => (
          <li id={n} onClick={e => this.toggle(e, i)}>
            {n}
          </li>
        ))}
      </ul>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

CodeSandbox here