react-将项目添加到处于特定索引状态的数组

时间:2018-07-09 19:58:00

标签: javascript reactjs react-native

我在reactjs中构建了一个应用程序im并响应本机。我的状态是要添加图像uri的数组。

        self.X=tf.placeholder(tf.float32, shape=[batch_size, 100,  num_features], name="input")

    with tf.variable_scope("LSTM_Initializer"):
        self.placeCellGround=tf.placeholder(tf.float32, shape=[batch_size, self.PlaceCells_units], name="Groud_Truth_Place_Cell")
        self.headCellGround=tf.placeholder(tf.float32, shape=[batch_size, self.HeadCells_units], name="Groud_Truth_Head_Cell")

        #Previous output of the cell
        self.hidden_state=tf.get_variable("LSTM_HiddenState", initializer=tf.random_normal((batch_size, self.Hidden_units), mean=0, stddev=1))
        #Memory of the cell
        self.cell_state=tf.get_variable("LSTM_CellState", initializer=tf.random_normal((batch_size, self.Hidden_units), mean=0, stddev=1))

        #INITIALIZE LSTM HIDDEN STATES AND INITAL STATES. BOTH OF SIZE [batch_size, Hidden_units]
        self.Wcp=tf.get_variable("Initial_state_cp", initializer=tf.random_normal((self.PlaceCells_units, self.Hidden_units), mean=0, stddev=1))
        self.Wcd=tf.get_variable("Initial_state_cd", initializer=tf.random_normal((self.HeadCells_units, self.Hidden_units), mean=0, stddev=1))
        self.Whp=tf.get_variable("Hidden_state_hp", initializer=tf.random_normal((self.PlaceCells_units, self.Hidden_units), mean=0, stddev=1))
        self.Whd=tf.get_variable("Hidden_state_hd", initializer=tf.random_normal((self.HeadCells_units, self.Hidden_units), mean=0, stddev=1))

        #Once this operation is called, self.hidden_state is update
        self.compute_hidden_state=tf.assign(self.hidden_state, tf.matmul(self.placeCellGround, self.Wcp) + tf.matmul( self.headCellGround, self.Wcd))
        #Once this operation is called, self.cell_state is update
        self.compute_cell_state=tf.assign(self.cell_state, tf.matmul(self.placeCellGround, self.Whp) + tf.matmul( self.headCellGround, self.Whd))

    with tf.variable_scope("LSTM"):
        #Define the single LSTM cell with a number of hidden states
        self.lstm_cell=tf.contrib.rnn.LSTMCell(self.Hidden_units, name="LSTM_Cell")

        #Store self.cell_state and self.hidden_state tensors as a single list
        initialize_states=tf.nn.rnn_cell.LSTMStateTuple(self.cell_state, self.hidden_state)

        #Creates RNN using cell type defined by cell= parameter.
        #dynamic_rnn allows to feed directly an input [batch_size, timesteps, features] without deconstruct it in a list of timesteps
        #OUTPUT IS A TENSOR OF SHAPE [batch_size, timesteps, hidden_units]
        #hidden_cell_statesTuple IS THE TUPLE THAT STORE THE TENSORS HIDDEN_STATE AND CELL_STATE AT THE END OF THE BATCH FED
        self.output, self.hidden_cell_statesTuple=tf.nn.dynamic_rnn(cell=self.lstm_cell, inputs=self.X, initial_state=initialize_states)

问题在于我想像这样在特定索引处向该数组添加图像uris

    const sqlite = require('sqlite');
    client.sql = sqlite;
    client.sql.open('database.sqlite')
    client.sql.get(`SELECT * FROM settings WHERE guildid =                                                         
    "${message.guild.id}"`).then(row => {
    if(!row) {
        client.sql.run(`INSERT INTO settings (guildid, prefix, 
        lang, color, admin, mod, user, autor, channel) VALUES 
        (?, ?, ?, ?, ?, ?, ?, ?, ?,)`, [message.author.id, 
        '!', 'en', '#ffffff', 'admin', 'mod', 'false', 
        'false', 'false'])
        client.gprefix = '!';
    } else {
        client.gprefix = row.prefix;
    }
}).catch(() => {
    client.sql.run(`CREATE TABLE IF NOT EXISTS settings 
    (guildid text UNIQUE, prefix text NOT NULL, lang text NOT 
    NULL, color text NOT NULL, admin text NOT NULL, mod text 
    NOT NULL, user text NOT NULL, autor text NOT NULL, channel 
    text NOT NULL`)
    client.sql.run(`INSERT INTO settings (guildid, prefix, 
    lang, color, admin, mod, user, autor, channel) VALUES (?, 
    ?, ?, ?, ?, ?, ?, ?, ?,)`, [message.author.id, '!', 'en', 
    '#ffffff', 'ad`enter code here`min', 'mod', 'false', 
    'false', 'false'])
        client.gprefix = '!';
})

但是,以上方法无效,有人可以向我指出正确的方向吗?

谢谢

3 个答案:

答案 0 :(得分:2)

使用Array.splice方法。

this.setState(prevState => {
  const { images } = prevState;
  images.splice(imageIndex, 0, result.uri);
  return images;
})

答案 1 :(得分:1)

您似乎正在尝试直接修改状态。请尝试以下方法:

pickImage = (imageIndex) => {
  let result = await ImagePicker.launchImageLibraryAsync({
            allowsEditing: true,
            aspect: [4, 3],
  });

  const images = { ...this.state };
  images[imageIndex] = result.uri;

  if (!result.cancelled) {
      this.setState({ images })
  }

答案 2 :(得分:0)

应使用该索引中的其他值创建一个新数组。我们要建立一个新数组,因为it is an antipattern to mutate state.可以通过复制this.state.images并修改特定索引处的值来创建。

const copyOfImages = [...this.state.images];
copyOfImages[imageIndex] = newValue;
this.setState({images: copyOfImages});

可以使用Array.prototype.map使此代码更具功能性。

this.setState(previousState => ({
  images: previousState.images.map(
    (image, index) => index === imageIndex ? result.uri : image
  );
});