Redux обновление объекта в массиве (React-Native) - PullRequest
0 голосов
/ 23 апреля 2020

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

Итак, я проверил, чтобы перейти к компоненту списка с данными, при сохранении будет выполнено действие UPDATE_LIST. Если вы перейдете к компоненту списка без данных, действие «сохранить» будет NEW_LIST. Новый список работает, а обновление - нет. Если вам нужно увидеть больше файлов, дайте мне знать. Спасибо.

Это компонент списка:

import React from 'react';
import { StyleSheet, Text, View, Button, TextInput } from 'react-native';
import { connect } from 'react-redux';
import { newList, updateList } from '../store/tagActions';


class List extends React.Component {
    constructor(props){
        super(props);

        this.state = {
            title: '',
            tags: [],
            mentions: [],

            tagValue: '',
            mentionValue: '',

            id: null
        }
    }

    submitTag = (text) => {
        this.setState({ 
            tags: [
                ...this.state.tags, 
                text
            ],
            tagValue: ''
        })
    }

    submitMention = (text) => {
        this.setState({
            mentions: [
                ...this.state.mentions,
                text
            ],
            mentionValue: ''
        })
    }

    componentDidMount() {
        if (this.props.route.params.data !== null) {
            const { title, tags, mentions, id } = this.props.route.params
            this.setState({ 
                id: id,
                title: title,
                tags: tags,
                mentions: mentions
            })
        } else return
    }

    save = () => {
        if (this.props.route.params.data !== null) {
            this.props.updateList(
                id = this.state.id,
                title = this.state.title,
                tags = this.state.tags,
                mentions = this.state.mentions
            )
        } else {
            this.props.newList(
                title = this.state.title, 
                tags = this.state.tags,
                mentions = this.state.mentions
            )
        }
        this.props.navigation.navigate('Home');
    }


    render() {

        return (
            <View style={styles.container}>
                <TextInput //==================================== TITLE
                    value={this.state.title}
                    style={styles.title}
                    placeholder='add Title..'
                    onChangeText={text => this.setState( {title: text} ) }
                />

                <View style={styles.allTags}>
                    <Text>{this.state.id}</Text>

                    <View style={styles.tagsList}>
                        {
                            this.state.tags.map((tag => (
                                <Text key={tag} style={styles.tags}>#{tag}</Text>
                            )))
                        }
                    </View>

                    <View style={styles.mentionsList}>
                        {
                            this.state.mentions.map((mention => (
                                <Text key={mention} style={styles.mentions}>@{mention}</Text>
                            )))
                        }
                    </View>

                </View>

                <TextInput // =================================== TAGS
                    value={ this.state.tagValue }
                    style={styles.tagsInput}
                    placeholder='add #Tags..'
                    placeholderTextColor = "#efefef"
                    autoCorrect = { false }
                    autoCapitalize = 'none'
                    onChangeText={text => this.setState( {tagValue: text}) }
                    onSubmitEditing={() => this.submitTag(this.state.tagValue)}
                />

                <TextInput //===================================== MENTIONS
                    value={ this.state.mentionValue }
                    style={styles.mentionsInput}
                    placeholder='add @Mentions..' 
                    placeholderTextColor = "#efefef"
                    autoCorrect = { false }
                    autoCapitalize = 'none'
                    onChangeText={text => this.setState( {mentionValue: text})}
                    onSubmitEditing= {() => this.submitMention(this.state.mentionValue)}
                />  

                <Button
                    title='save'
                    onPress={() => {
                            this.save();
                        }
                    }
                />


            </View>
        )
    }
}

const mapStateToProps = (state) => {
    return { state }
  };



export default connect(mapStateToProps, { newList, updateList }) (List);

tagActions. js

let nextId = 0;

export const newList = (title, tags, mentions) => (
    {
        type: 'NEW_LIST',
        payload: {
            id: ++nextId,
            title: title,
            tags: tags,
            mentions: mentions
        }
    }
);

export const updateList = (title, tags, mentions, id) => (
    {
        type: 'UPDATE_LIST',
        payload: {
            id: id,
            title: title,
            tags: tags,
            mentions: mentions
        }
    }
);

tagReducer. js:

const tagReducer = (state = [], action) => {

    switch (action.type) {

        case 'NEW_LIST':
             //add tags and mentions later
            const { id, title, tags, mentions } = action.payload;
            return [
                ...state,
                {
                    id: id,
                    title: title,
                    tags: tags,
                    mentions: mentions
                }
            ]
        case 'UPDATE_LIST':

            return state.map((item, index) => {
                if (item.id === action.payload.id) {
                    return { 
                        ...item,
                        title: action.payload.title,
                        tags: action.payload.tags,
                        mentions: action.payload.mentions
                    }
                } else { return item }

            })

        default: 
            return state;
    }
};


export default tagReducer;

1 Ответ

1 голос
/ 23 апреля 2020

Посылая такие аргументы как


export const updateList = (title, tags, mentions, id) => (

В области действия функции первый аргумент, с которым будет вызываться функция, будет title, и даже при выполнении что-то вроде этого


  this.props.updateList(
            id = this.state.id,
            title = this.state.title,
            tags = this.state.tags,
            mentions = this.state.mentions
        )

, которое вы отправили как this.state.id, будет оцениваться как title. (не python alert)

, поэтому у вас есть два варианта: либо упорядочить аргументы как в функции, либо отправить объект с помощью клавиш


  this.props.updateList({
            id: this.state.id,
            title: this.state.title,
            tags: this.state.tags,
            mentions: this.state.mentions
        })

  export const updateList = ({title, tags, mentions, id}) => (

В любом случае, конечно Вы можете использовать массив в качестве структуры данных для состояния, извините, я ввел вас в заблуждение


     const tagReducer = (state = [], action) => {
      switch (action.type) {
       const { id, title, tags, mentions } = action.payload || {};
       case 'NEW_LIST':
         //add tags and mentions later
        return [ ...state, { id, title, tags, mentions } ]

       case 'UPDATE_LIST':
        return state.map(item => 
             item.id === id ? { ...item, title, tags, mentions} : item 
            )

       default: return state;
     }
   };


   export default tagReducer;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...