React Native - элементы AsyncStorage в плоский список - PullRequest
0 голосов
/ 31 мая 2018

Я пытаюсь отобразить / сохранить список элементов в моем плоском списке, но проблема заключается в том, что когда я сохраняю элемент и загружаю этот элемент на другом экране, он находится в некотором повторении (посмотрите на снимок экрана),И когда я пытаюсь добавить другой элемент, этот новый элемент заменит предыдущий элемент с таким же видом повторения.То, на что я нацеливаюсь - это иметь список.

List_ScreenShot

Вот мой код

AddModal.js

export default class AddModal extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          modalVisible: props.modalVisible,
          id: null,
          count: 0,
          price: null
        };
    }

    state = {
        text: '',
    }

    save = () => {
        const { text } = this.state;
        let myArray = {
            text, text
        }
        AsyncStorage.setItem('myArray', JSON.stringify(myArray));
        alert(text + 'saved');
    }

    onChange = (text) => {
        this.setState({ text });
    }

    componentWillReceiveProps(nextProps) {
        this.setState({
          modalVisible: nextProps.modalVisible,
            id: nextProps.id,
            price: nextProps.price
        })
    }

    render() {
      console.log('inside AppModal', this.state.modalVisible);
        return (
                <View>
                    <TextInput style = { styles.input }
                        keyboardType = "numeric"
                        onChangeText = { this.onChange }
                        value = { this.state.text }       //Item **
                     >
                     </TextInput>
                </View>

                <View}>
                     <TouchableOpacity
                        onPress = {() => { this.props.setModalVisible(false) }}
                                    >
                           <Text style = { styles.buttonText }>Cancel</Text>
                     </TouchableOpacity>

                     <TouchableOpacity
                        onPress = { this.save }>
                           <Text style = { styles.buttonText }>Send</Text>
                     </TouchableOpacity>
                 </View>
        )
    }
}

Settlment.js

import Details from '../Menus/Details';
const key = '@MyApp:key';
export default class Settlement extends React.Component {
    state = {
        text: '',
        storedValue: '',
        myArray: ''
    }

      componentWillMount() {
        //this.onLoad();
        AsyncStorage.getItem('myArray')
        .then(text => this.setState({ text }));
    }

    showData = async() => {
        let myArray = await AsyncStorage.getItem('myArray');
        let d = JSON.parse(myArray);
        this.setState({ myArray : myArray });
    }

  render() {
      const { myArray, text } = this.state;
    return (
        <View>
            <TouchableOpacity onPress = {this.showData}>
                <Text>Load Data</Text>
            </TouchableOpacity>
            <FlatList data = { this.state.myArray }
                renderItem = {({ item }) => 
                    <Text>{myArray}</Text>
                }
                keyExtractor={(item, index) => index.toString()}
            >
            </FlatList>
        </View>
    );
  }
}

1 Ответ

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

То, что я вижу здесь:

      const { text } = this.state;
    let myArray = {
        text, text
    }
    AsyncStorage.setItem('myArray', JSON.stringify(myArray));
    alert(text + 'saved');

- это объект с именем myArray, и к нему ничего не добавляется.Он определяется, а затем присваивается значение.

Может быть, вы могли бы объявить свой массив в другом месте, как в конструкторе (как массив, а не объект, используя myArray = []), а затем использовать myArray.push(text) или, если вы хотите массив, содержащий объекты, вы можете выдвинуть объект, используяmyArray.push({ yourKeyName: text }).Кроме того, кажется, что объект, который вы храните в AsyncStorage, заменяется и не добавляется.Но я не уверен, почему вы получаете несколько элементов списка вместо одного.

PS - Где вы объявляете состояние выглядит немного не так.Я обычно вижу это так:

constructor() {
    super();
    this.state = { 
        text: '',
        storedValue: '',
        myArray: '',
    };
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...