React Native - изменение состояний в массиве другого файла - PullRequest
0 голосов
/ 04 июня 2018

Привет всем :) Это мой первый пост, надеюсь, я все делаю правильно!

В настоящее время я работаю над школьным проектом и уже несколько недель использую реагирующий на нём.

Моя проблема:

У меня есть файл data.js:

const cardOne_1 = require("../images/Vergleiche/Eisbär.jpg");
const cardTwo_1 = require("../images/Vergleiche/Android.jpg");
const cardThree_1 = require("../images/Vergleiche/Han_Solo_Alt.jpg");

const cardOne_2 = require("../images/Vergleiche/Gorilla.jpg");
const cardTwo_2 = require("../images/Vergleiche/Apple.jpg");
const cardThree_2 = require("../images/Vergleiche/Han_Solo_Jung.jpg");


 export default[
  {
    image: cardOne_1,
    image2: cardOne_2,
    text: '53%',
    text2: '47%',
    title: 'Icebear vs Gorilla',
    check: false,

  },
  {
    image: cardTwo_1,
    image2: cardTwo_2,
    text: '19%',
    text2: '81%',
    title: 'Android vs IOS',
    check: true,

  },
  {
    image: cardThree_1,
    image2: cardThree_2,
    text: '70%',
    text2: '30%',
    title: 'Han Solo',
    check: false,
  },
];

Мой рабочий стол содержит два из этих Deckswiper (для большей ясности я покажу здесь только коддля первого), которые используются для сравнения двух изображений: Домашний экран - с двумя DeckSwiper

import data from '../Data.js';

export default class SwipeCards2 extends Component {
  _onSwipeLeft() {
    this._deckSwiper1._root.swipeLeft();
    this._deckSwiper2._root.swipeRight();
  }

  _onSwipeRight() {
    this._deckSwiper2._root.swipeLeft();
    this._deckSwiper1._root.swipeRight();
  }
  render() {
    return (
      <Container style={{ backgroundColor: '#ffffff' }}>
        <View>
          <DeckSwiper
            ref={mr => (this._deckSwiper1 = mr)}
            dataSource={data}
            onSwipeRight={() => this._deckSwiper2._root.swipeLeft()}
            onSwipeLeft={() => this._deckSwiper2._root.swipeRight()}
            looping={true}
            renderEmpty={() => (
              <View style={{ alignSelf: 'center' }}>
                <Text>Das war´s!</Text>
              </View>
            )}
            renderItem={item => (
              <Card
                style={{
                  elevation: 3,
                  height: 335,
                  justifyContent: 'center',
                  width: Dimensions.get('window').width + 1,
                  marginLeft: -1,
                  marginTop: 0,
                }}>

                <TouchableWithoutFeedback onPress={() => this._onSwipeRight()}>

                  <CardItem cardBody style={{ alignItems: 'center' }}>
                    <Image
                      style={{
                        resizeMode: 'cover',
                        flex: 1,
                        height: 335,
                      }}
                      source={item.image}
                    />
                  </CardItem>
                </TouchableWithoutFeedback>

              </Card>
            )}
          />

        </View>
      </Container>
    );
  }
}

Я хочу установить состояние "check" в data.js в true,каждый раз, когда пользователь проводит пальцем вправо.

Третий экран отображает компонент List, который должен отображать ранее принятые решения пользователя.Этот список основан на «проверке» data.js.

Экран 3 - Список всех решений

Я пытался почти три дня и не могу найти какое-либо хорошее решение!

У вас есть какие-либопредложения как этого добиться?

Спасибо :))

1 Ответ

0 голосов
/ 04 июня 2018

Я не уверен, как обстоят дела с этим компонентом DeckSwiper, но, поскольку вы импортируете статические данные, если вам нужно изменить данные, вам нужно их клонировать, а затем изменить.Присвоение клона данных переменной состояния, а затем передача его компоненту будет отражать изменения компонента.

Чтобы изменить свойство определенного объекта в вашем массиве, вам также потребуется уникальный идентификатор, такой как идентификатор или аналогичный.,

Пример

import data from '../Data.js';

export default class SwipeCards2 extends Component {
  constructor(props) {
    super(props);
    // clone the static data to state
    this.state = {
      data: [...data]
    }
  }
  changingCheckFunction(obejctsUniqueId) {
    this.setState((prevState) => {
       // find the object's id
      const itemIndex = prevState.data.findIndex(x => x.id == obejctsUniqueId);
      // copy the item and assign the new checked value
      const newItem = Object.assign({}, prevState.data[itemIndex], { checked: !prevState.data[itemIndex]}); 
      // copy the previous data array
      const newData = [...prevState.data];
      // set the newItem to newData
      newData[itemIndex] = newItem;
      // return the new data value to set state
      return { data: newData };
    });
  }
  _onSwipeLeft() {
    this._deckSwiper1._root.swipeLeft();
    this._deckSwiper2._root.swipeRight();
  }

  _onSwipeRight() {
    this._deckSwiper2._root.swipeLeft();
    this._deckSwiper1._root.swipeRight();
  }
  render() {
    return (
      <Container style={{ backgroundColor: '#ffffff' }}>
        <View>
          <DeckSwiper
            ref={mr => (this._deckSwiper1 = mr)}
            dataSource={this.state.data}
            onSwipeRight={() => this._deckSwiper2._root.swipeLeft()}
            onSwipeLeft={() => this._deckSwiper2._root.swipeRight()}
            looping={true}
            renderEmpty={() => (
              <View style={{ alignSelf: 'center' }}>
                <Text>Das war´s!</Text>
              </View>
            )}
            renderItem={item => (
              <Card
                style={{
                  elevation: 3,
                  height: 335,
                  justifyContent: 'center',
                  width: Dimensions.get('window').width + 1,
                  marginLeft: -1,
                  marginTop: 0,
                }}>

                <TouchableWithoutFeedback onPress={() => this._onSwipeRight()}>

                  <CardItem cardBody style={{ alignItems: 'center' }}>
                    <Image
                      style={{
                        resizeMode: 'cover',
                        flex: 1,
                        height: 335,
                      }}
                      source={item.image}
                    />
                  </CardItem>
                </TouchableWithoutFeedback>

              </Card>
            )}
          />

        </View>
      </Container>
    );
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...